Django formset验证所有表单

时间:2013-02-18 09:52:10

标签: django validation django-forms formset

我制作了这样的表格。

class MixedObsCollsForm(forms.Form):

    def __init__(self, *args, **kwargs):
        project_id = kwargs.pop('project_id')
        super(MixedObsCollsForm, self).__init__(*args, **kwargs)
        project = get_object_or_404(Project, pk=project_id)
        self.fields['photos_upload'] = forms.ImageField(label="Photos", required=False)

    taxon = forms.CharField(max_length=80, required=False)
    growth_form = forms.ChoiceField(choices = growthFormChoice, required=False)
    height = forms.DecimalField(max_value=99, min_value=0, decimal_places=2, required=True)
    density = forms.IntegerField(max_value=100, min_value=1, required=False)

我有一种奇怪的方式在视图中使用类来处理所有处理。但就像这样...

class ObservationFormView(object):    

    def __init__(self, request=None, project_id=None, observation_id=None):

        self.request = request
        self.ObservationFormSet = formset_factory(form=MixedObsCollsForm, extra=5)
        self.ObservationFormSet.form = staticmethod(curry(MixedObsCollsForm, project_id=project_id)) 
        self.project = get_object_or_404(Project, pk=project_id)



        self.user = request.user

        self.use_type = 'create'
        self.formset = self.ObservationFormSet(self.request.POST or None)


    def isValid(self):
        return self.formset.is_valid() & self.locationForm.is_valid()

    def render(self):
        return render(self.request, 'observation_form.html', {'use_type': self.use_type, 'formset': self.formset, 'locationForm':self.locationForm, 'project_photos': self.project.photos.all(),})

    def processForm(self):     

        for form in self.formset:
            if form.is_valid() == True:
                if form.cleaned_data['is_collection'] == True:
                    collection = self.getOrMakeCollection(form.cleaned_data, self.locationForm.cleaned_data['location'], False)
                if form.cleaned_data['is_collection'] == False:
                    collection = self.getOrMakeCollection(form.cleaned_data, self.locationForm.cleaned_data['location'], True)

                observation = self.saveObservation(form.cleaned_data, self.locationForm.cleaned_data['location'], collection)


        return observation

问题是当我在视图中呈现此表单时,即使formset中的表单为空也不会验证。报告“此字段是必填项”。在所有高度字段旁边。即使是空洞的。

我的理解是空表单应该始终通过验证。我查看了管理表格数据,看起来都很好。

如果我将required更改为False,则意味着当我尝试将formset保存到数据库时,我最终会遇到IntegrityErrors。

1 个答案:

答案 0 :(得分:1)

我终于弄清楚它是什么,所以这里有任何有这个问题的人,很容易被忽视。

它甚至没有包含在问题的代码中,所以没有人能提供太多的帮助。

这一行:

growth_form = forms.ChoiceField(choices = growthFormChoice, required=False)

使用growthFormChoice变量,这是一个像这样的选择元组。

growthFormChoice = (('0', 'Select one'),
                    ('T', 'tree'),  
                    ('S', 'shrub'))

因此,默认值('0':'Select One')导致将0传递给未(有意)更改的每个表单,并触发其余字段的验证。只需将其更改为('':'Select One')即可。