如何从表单中的验证中排除少数字段

时间:2013-05-17 03:52:33

标签: django forms validation

我有像这样的Django形式的10个字段

class SearchForm(forms.Form):
    student_number                 = forms.CharField(required=False)
    final_date                      = forms.DateField(required=False)
    location_area                   = forms.FloatField(required=False)

在我的form.is_valid()中,我想从验证中排除少数字段,例如

[location_area, final_date]并且全部执行验证或只想验证charfields而不是select fields

我该怎么做?

2 个答案:

答案 0 :(得分:2)

Meta表格中,您可以排除字段:

class SearchForm(forms.Form):
    # form fields here
    class Meta:
        exclude = ('location_area', 'final_date',)

如果您不想从表单中排除字段并仍然不想验证它们,那么为表单执行任何操作的自定义字段清理方法:

class SearchForm(forms.Form):
    # form fields here

    def clean_location_area(self):
        location_area = self.cleaned_data['location_area']
        return location_area

答案 1 :(得分:0)

基本上,您可以覆盖表单的 init 方法: 例如

class SearchForm(forms.Form):
# form fields here

def __init__(self, post_data=None, post_files=None):
     if post_data and post_files:
         self.base_fields.remove(field_name)
         super(SearchForm, self).__init__(post_data, post_files)
     else:
         super(SearchForm, self).__init__()

因此,基本上,您在获得表格时可以使用:SearchForm() 在将数据发布到表单时,您可以使用:SearchForm(request.POST, request.FILES)。 在__init__方法中,我们使用post_datapost_files检查请求是发布还是获取。因此,如果它是发布的,我们将从base_field中删除该字段,以便它不会检查该字段的有效性。

在Django 1.11中测试