1

我做了一个这样的表单集。

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

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

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

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

4

1 回答 1

1

我终于弄清楚了它是什么,所以对于其他有这个问题的人来说,它很容易被忽视。

它甚至没有包含在问题的代码中,因此任何人都无法提供太多帮助。

这一行:

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

使用了growthFormChoice像这样的选择元组的变量。

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

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

于 2013-02-18T15:16:58.723 回答