【问题标题】:Give values to each form in a formset in Django在 Django 中为表单集中的每个表单赋值
【发布时间】:2013-04-07 22:09:49
【问题描述】:

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

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 发送到每个表单,但我不确定如何执行此操作。我也觉得我应该提到表单集的表单数量应该与申请人查询中的申请人完全相同。

【问题讨论】:

    标签: django forms dynamic formset


    【解决方案1】:

    您可以编写自定义表单集。

    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)
    

    【讨论】:

    • 哇,这太完美了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 2016-01-08
    • 2013-04-03
    • 2010-12-26
    • 2014-03-13
    • 2014-11-09
    • 1970-01-01
    相关资源
    最近更新 更多