0

我正在尝试创建一个表单集,每个表单集都包含一个输入字段。这将有一些动态数量的元素,一旦提交表单,输入的文本将作为“标签”分配给关联的对象。这可能听起来有点令人困惑,所以让我们看看我正在尝试制作的表单类:

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 表单,然后在收到 post 请求后,通过调用每个表单 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 的初始表单集。理想情况下,我可以遍历查询集并将申请人.id 发送到每个表单,但我不确定如何执行此操作。我也觉得我应该提到表单集应该具有与申请者查询中的申请人完全相同的表单数量。

4

1 回答 1

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]

现在您不需要覆盖__init__TagsForm。

现在,您的每个表格都与申请人相关联。因此,您可以删除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)
于 2013-04-15T19:30:49.977 回答