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

问题描述 投票:1回答:2

我有像这样的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

我怎样才能做到这一点?

django forms validation
2个回答
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

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。因此,如果它是post,我们将从base_field中删除该字段,以便它不会检查该字段的验证。

在Django 1.11中测试过

© www.soinside.com 2019 - 2024. All rights reserved.