2013-10-18 87 views
1

切換到內聯表單集我結束了之後:Django的保存多個在線表單集

def dns_view(request, domain): 
    dnszone = get_object_or_404(DNSSQL, zone = domain) 

    form1 = EditDNSZone(instance = dnszone) 
    forms = EditDNSEntry(instance = dnszone, prefix = 'entries') 
    formsmx = EditDNSEntryMX(instance = dnszone, prefix = 'mxentries') 

試圖拯救所有形式,我設法僅保存Form1中後。 如何保存所有表格?

回答

1

Django的formset適用於同一表單的多個實例。您正在嘗試保存多個表單類,而這些表單並不適用於此。

一種方法是構建一個表單,其中包含您想要包含的表單中的所有字段,並在處理表單時創建要處理的每個表單。以下是一個簡單的例子。你也可以通過反思模型和自動創建模型表單來做一些事情,但這是一個長期的故事......

class Form1(forms.Form): 
    a_field = forms.CharField() 


class Form2(forms.Form): 
    b_field = forms.CharField() 


class MainForm(forms.Form): 
    a_field = forms.CharField() 
    b_field = forms.CharField() 
    def __init__(self, **kwargs): 
    super(MainForm, self).__init__(**kwargs) 
    # This will work because the field name matches that of the small forms, data unknow to 
    # a form will just be ignored. If you have something more complex, you need to append 
    # prefix, and converting the field name here. 
    form1 = Form1(**kwargs) 
    form2 = Form2(**kwargs) 
+0

好的,任何建議什麼是最好的方法? –