【问题标题】:Is clean_<fieldname> supported in ModelForm?ModelForm 是否支持 clean_<fieldname>?
【发布时间】:2015-11-29 18:08:06
【问题描述】:

在 ModelForm 的 documentation 中被告知,要对表单执行自定义验证,必须重写 .clean() 方法。

但是,我更喜欢使用clean_&lt;fieldname&gt; 方法,因为我只需要验证一个字段。这适用于标准的forms.Form,但对于forms.ModelForm 的关注点没有提及。

Django 是否支持这种方法?

【问题讨论】:

  • 是的,支持。

标签: django modelform


【解决方案1】:

是的,当然。请参见下面给出的示例。

class UserForm(form.ModelForm):

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'website', 'twitter','facebook', 'linkedin',
                  'glassdoor', 'github',)

    def clean_github(self):
        github = self.cleaned_data.get('github')
        if github and not re.match(r'^[a-zA-Z0-9-]+$', github):
            raise forms.ValidationError('Please enter a valid github username')
        return github

【讨论】:

    猜你喜欢
    • 2019-06-14
    • 1970-01-01
    • 2011-06-02
    • 2012-04-06
    • 1970-01-01
    • 2013-02-01
    • 2015-05-29
    • 1970-01-01
    • 2020-08-08
    相关资源
    最近更新 更多