【问题标题】:Django ModelForm, custom validationDjango ModelForm,自定义验证
【发布时间】:2012-05-23 05:14:11
【问题描述】:

我有一个很大的表格,有两种可能性。它是事件的一种形式,事件位置可以从组合框(ModelChoice 查询)中选取。但是,用户可以选中“新位置”复选框,然后表单也会显示插入新位置所需的字段,并且“现有位置”组合框会被重置。现在,这一切都适用于 javascript (jQuery),但我的问题是如何验证表单中未使用的字段。

简单地说> 我有 7 个表单文件,其中 3 个始终是强制性的(事件类型、日期时间等),而另一个取决于复选框“新位置”的状态:如果选中了新位置>验证位置等字段,忽略其余部分(允许它们为空),否则忽略位置字段并验证其余部分。

class EventForm(ModelForm):

    area = forms.ModelChoiceField(
        queryset=Area.objects.order_by('name').all(),
        empty_label=u"Please pick an area",
        label=u'Area',
        error_messages={'required':u'The area is mandatory!'})

    type = forms.ModelChoiceField(
        queryset=SportType.objects.all(),
        empty_label=None,
        error_messages={'required':'Please pick a sport type!'},
        label=u"Sport")

    #shown only if new_location is unchecked - jQuery
    location = forms.ModelChoiceField(
        queryset=Location.objects.order_by('area').all(),
        empty_label=u"Pick a location",
        error_messages={'required':'Please pick a location'},
        label=u'Location')

    #trigger jQuery - hide/show new location field
    new_location = forms.BooleanField(
        required=False,
        label = u'Insert new location?'
            )

    address = forms.CharField(
        label=u'Locatio address',
        widget=forms.TextInput(attrs={'size':'30'}),
        error_messages={'required': 'The address is required'})

    location_description = forms.CharField(
        label=u'Brief location description',
        widget=forms.Textarea(attrs={'size':'10'}),
        error_messages={'required': 'Location description is mandatory'})

    class Meta:
        model = Event
        fields = (
            'type',
            'new_location',
            'area',
            'location',
            'address',
            'location_description',
            'description',
        )

【问题讨论】:

    标签: django forms validation


    【解决方案1】:

    我最终只使用了普通表单(不是 ModelForm)和 clean(self) 的自定义验证,具体取决于复选框的状态,我认为这是正确的方法。然后使用self._errors["address"]=ErrorList([u'Some custom error']),我能够完全自定义验证过程中可能出现的各种错误。

    【讨论】:

    • 你是怎么把它提交到数据库的,因为如果你使用普通形式,对象不会继承建模保存方法。
    【解决方案2】:

    您可以检查clean 方法中的表单字段是否存在。如果存在,请在其上运行您的自定义验证规则。

    def clean(self):
        cleaned_data = self.cleaned_data
        field_name = cleaned_data.get('FIELD_NAME', None)
    
        if field_name:
        ... # do stuff
        return cleaned_data
    

    【讨论】:

      猜你喜欢
      • 2012-09-30
      • 2014-08-05
      • 2013-02-12
      • 1970-01-01
      • 2013-11-26
      • 2013-08-22
      • 2011-01-09
      • 2016-07-01
      相关资源
      最近更新 更多