Django Formsets - 如何正确构建一个formset并验证它?

时间:2013-01-11 15:07:41

标签: django django-forms

我正在使用Django 1.4而且我正在努力使用Formsets。我已经阅读了文档和很多SO问题。我已经找不到他们真正工作的线索了。

- 应该像这样配置/刻录Fomsets吗?

我如何在forms.py和views.py中设置formset。

forms.py :(我已声明了forms.Form)

class BicycleAdItemKindPropertyValueForm(forms.Form):
    bicycleaditemkindpropertyvalue = forms.ChoiceField()

views.py:

def submit_ad_view(request):

    # This class is used to make empty formset forms required
    class BicycleAdItemKindPropertyValueFormSet(BaseFormSet):
        def __init__(self, *args, **kwargs):
            super(BicycleAdItemKindPropertyValueFormSet, self).__init__(*args, **kwargs)
            for form in self.forms:
                form.empty_permitted = False

        def clean(self):
            pdb.set_trace()  
            for form in self.forms:
                None
            #form.fields['bicycleaditemkindpropertyvalue']

    formsetBicycleAdItemKindPropertyValue = formset_factory(BicycleAdItemKindPropertyValueForm, formset=BicycleAdItemKindPropertyValueFormSet)

    if request.method == 'POST':      
        model_main = Main()
        model_main.section = Section.objects.get(pk=request.POST['section'])
        model_main.user = request.user

        model_bicyclead = BicycleAd()
        model_bicyclead.bicycleadtype = BicycleAdType.objects.get(pk=2) #1-Ad Link, 2-Ad Insite. Em principio ficara pre-definido
        model_bicyclead.bicycleaditemkind = BicycleAdItemKind.objects.get(pk=4) 
        model_bicyclead.bicycleadcondition = BicycleAdCondition.objects.get(pk=2)
        model_bicyclead.city = GeonamesLocal.objects.get(pk=4803854)

        # Build the forms
        form_main = MainForm(request.POST, instance = model_main)
        form_bicyclead = BicycleAdForm(request.POST, instance = model_bicyclead)
        form_bicycleadcategory = BicycleAdCategoryForm(request.POST)
        form_bicycleaditemkindselect = BicycleAdItemKindSelectForm(request.POST)
        formset_bicycleaditemkindpropertyvalue = formsetBicycleAdItemKindPropertyValue(request.POST)

        #pdb.set_trace()

        if form_main.is_valid() and form_bicyclead.is_valid() and form_bicycleadcategory.is_valid() and form_bicycleaditemkindselect.is_valid() and formset_bicycleaditemkindpropertyvalue.is_valid():
            main_f = form_main.save()

            bicyclead_f = form_bicyclead.save(commit=False)
            bicyclead_f.main = main_f
            bicyclead_f.save()

            bicycleadcategory_f = form_bicycleadcategory.save(commit=False, rel_obj=model_bicyclead)  


    else:
        # Build the forms
        form_main = MainForm()
        form_bicyclead = BicycleAdForm()
        form_bicycleadcategory = BicycleAdCategoryForm()
        form_bicycleaditemkindselect = BicycleAdItemKindSelectForm()
        formset_bicycleaditemkindpropertyvalue = formsetBicycleAdItemKindPropertyValue()

    return render_to_response('app/submit/submit_ad.html', {'form_main': form_main, 'form_bicyclead': form_bicyclead, 'form_bicycleadcategory': form_bicycleadcategory, 'form_bicycleaditemkindselect': form_bicycleaditemkindselect, 'formset_bicycleaditemkindpropertyvalue': formset_bicycleaditemkindpropertyvalue}, context_instance=RequestContext(request))

这两个前面的步骤是否正确? formset被正确声明了吗?

现在,模板。我已经这样声明了:

sometemplate.html:

{{formset_bicycleaditemkindpropertyvalue.management_form}}
{{formset_bicycleaditemkindpropertyvalue.non_form_errors}}
{{formset_bicycleaditemkindpropertyvalue.errors}}
{% for form in formset_bicycleaditemkindpropertyvalue.forms %}
<div class="item-bicycleaditemkindpropertyvalue">
    <label for="{{form.bicycleaditemkindpropertyvalue.auto_id}}"></label>
    {{form.bicycleaditemkindpropertyvalue}}
</div>

在JavaScript的帮助下,代码将生成如下内容:

<form action="/submeter/anuncio/" method="post"><div style="display: none;"><input type="hidden" value="3TWjKpqnXG7afZcvF1YmmWcRBKnYqePB" name="csrfmiddlewaretoken"></div>
...         
        <div class="someclass">
            <input type="hidden" id="id_form-TOTAL_FORMS" value="1" name="form-TOTAL_FORMS">
            <input type="hidden" id="id_form-INITIAL_FORMS" value="0" name="form-INITIAL_FORMS">
            <input type="hidden" id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS">
            []
            <div class="item-bicycleaditemkindpropertyvalue">
                <label for="id_form-0-bicycleaditemkindpropertyvalue">Some 0</label>
                <select id="id_form-0-bicycleaditemkindpropertyvalue" name="form-0-bicycleaditemkindpropertyvalue">
                    ...
                </select>
            </div><div class="item-bicycleaditemkindpropertyvalue">
                <label for="id_form-1-bicycleaditemkindpropertyvalue">Some 1</label>
                <select id="id_form-1-bicycleaditemkindpropertyvalue" name="form-1-bicycleaditemkindpropertyvalue">
                    ...
                </select>
            </div>
            <div class="item-bicycleaditemkindpropertyvalue">
                <label for="id_form-2-bicycleaditemkindpropertyvalue">Some 2</label>
                <select id="id_form-2-bicycleaditemkindpropertyvalue" name="form-2-bicycleaditemkindpropertyvalue">
                    ...
                </select>
            </div>      
        </div>
        <input type="submit">
</form>

输出是否正确?应该是这样的吗?

- 验证,如何验证表单集?

现在关于验证。我的表单中有一个forms.ChoiceField()

class BicycleAdItemKindPropertyValueForm(forms.Form):
    bicycleaditemkindpropertyvalue = forms.ChoiceField()

我已经读过,应该根据选择列表验证forms.ChoiceField()。我的问题是我该怎么做?

- 一些信息调试

在clean()中使用pdb(python debuger)我看到我得到了这个数据:

class BicycleAdItemKindPropertyValueFormSet(BaseFormSet):
    def __init__(self, *args, **kwargs):
        super(BicycleAdItemKindPropertyValueFormSet, self).__init__(*args, **kwargs)
        for form in self.forms:
            form.empty_permitted = False

    def clean(self):
        pdb.set_trace()  
        for form in self.forms:
            None
        #form.fields['bicycleaditemkindpropertyvalue']

调试self.data:

(Pdb) self.data
<QueryDict: {u'form-1-bicycleaditemkindpropertyvalue': [u'29'], 
             u'form-2-bicycleaditemkindpropertyvalue': [u'33'], 
             u'title': [u'adasd'], 
             u'form-MAX_NUM_FORMS': [u''], 
             u'country': [u'42'], 
             u'section': [u'5'], 
             u'item_kind': [u'4'], 
             u'form-INITIAL_FORMS': [u'0'], 
             u'bicycleadcategorytype': [u'3', u'2'], 
             u'csrfmiddlewaretoken': [u'3TWjKpqnXG7afZcvF1YmmWcRBKnYqePB'], 
             u'form-TOTAL_FORMS': [u'3'], 
             u'form-0-bicycleaditemkindpropertyvalue': [u'4']}>

调试self.is_valid():

(Pdb) self.is_valid()
False

有关如何验证此formset的任何线索?

最诚挚的问候,

1 个答案:

答案 0 :(得分:0)

上述代码中的formset被正确声明。此外,生成的输出是formset生成它的理想方式。关于验证表单,您可以这样做。

for form in formset:
    if form.is_valid():
        # If is valid do something here
    else:
        # Do something Else

如果你想自己做验证,你可以覆盖clean类下的form方法,因为is_valid方法调用了这个方法。

class BicycleAdItemKindPropertyValueForm(forms.Form):
    bicycleaditemkindpropertyvalue = forms.ChoiceField()


    def clean(self):
        # Do field validation here.

如果您希望验证并且只有一个字段,则可以覆盖clean_field方法,如下所示:

class BicycleAdItemKindPropertyValueForm(forms.Form):
    bicycleaditemkindpropertyvalue = forms.ChoiceField()

    def clean_bicycleaditemkindpropertyvalue(self):
        # Do single field validation here.