2013-04-15 54 views
0

我想創建一個每個包含一個輸入字段的表單集。這將有一些動態元素,並且一旦表單被提交,輸入的文本將被分配爲「標籤」給關聯的對象。這可能聽起來樣的混亂,從而讓我們看看窗體類,我試圖讓:在Django的表單中爲每個表單賦值

class TagsForm(forms.Form): 

    tags = forms.CharField() 
    def __init__(self, *args, **kwargs): 
     applicantId = kwargs.pop('applicantId') 

    def saveTags(self): 
     applicant = Applicants.objects.get(id=applicantId) 
     Tag.update(applicant,tags) 

正如你可以看到,我想通過形式的申請者的ID,然後在recieving發佈請求更新標籤通過調用每個表單saveTags爲該申請人提供對象。下面是我的看法,我正在處理這個代碼:

... 
    applicantQuery = allApplicantsQuery.filter(**kwargs) 
    TagsFormSet = formset_factory(TagsForm) 
    if request.method == 'POST': 
     tags_formset = TagsFormSet(request.POST, request.FILES, prefix='tags') 
     if tags_formset.is_valid() 
      for tagForm in tags_formset: 
       tagForm.saveTags() 
    else: 
     tags_formset = TagsFormSet(prefix='tags') 
    ... 

的問題是我不知道如何創建一個ID的距離applicantQuery查詢集的初始設置的形式。理想情況下,我可以循環查詢集並將applicant.id發送給每個表單,但我不知道如何執行此操作。我也覺得我應該提到formset應該和applicantsQuery中的申請人數量完全一樣。

回答

2

您可以編寫自定義的表單。

from django.forms.formsets import BaseFormSet 

class TagFormSet(BaseFormSet): 

    def __init__(self, *args, **kwargs): 
     applicants = kwargs.pop('applicants') 
     super(TagFormSet, self).__init__(*args, **kwargs) 
     #after call to super, self.forms is populated with the forms 

     #associating first form with first applicant, second form with second applicant and so on 
     for index, form in enumerate(self.forms): 
      form.applicant = applicants[index] 

現在你不需要重寫TagsForm的__init__

現在您的每個表格都與申請人相關聯。因此,您可以刪除saveTags()的第一行。所以saveTags()成爲:

def saveTags(self): 
    #applicant was set on each form in the init of formset 
    Tag.update(self.applicant, tags) 

您的視圖代碼:

applicantQuery = allApplicantsQuery.filter(**kwargs) 

#notice we will use our custom formset now 
#also you need to provide `extra` keyword argument so that formset will contain as many forms as the number of applicants 
TagsFormSet = formset_factory(TagsForm, formset=TagFormSet, extra=applicantQuery.count()) 

if request.method == 'POST': 
    tags_formset = TagsFormSet(request.POST, request.FILES, prefix='tags', applicants=applicantQuery) 
    if tags_formset.is_valid() 
     for tagForm in tags_formset: 
      tagForm.saveTags() 
else: 
    tags_formset = TagsFormSet(prefix='tags', applicants=applicantQuery) 
+0

哇,這是完美的!謝謝! – James

相關問題