【问题标题】:How don't call clean_<fieldname> method in 'required=False' field?如何不在 'required=False' 字段中调用 clean_<fieldname> 方法?
【发布时间】:2013-04-24 04:38:01
【问题描述】:

如何不在 'required=False' 字段中调用 clean_ 方法?

forms.py

from django import forms

class userRegistrationForm(forms.Form):
    username = forms.CharField(
        max_length=30,
    )
    password1 = forms.CharField(
        widget=forms.PasswordInput(),
    )

    email = forms.EmailField(  # If user fill this, django will call 'clean_email' method.
        required=False,  # But when user don't fill this, I don't want calling 'clean_email' method.
    )

    def clean_email(self):
        if 'email' in self.cleaned_data:
            try:
                User.objects.get(email=self.cleaned_data['email'])
            except ObjectDoesNotExist:
                return self.cleaned_data['email']
            else:
                raise forms.ValidationError('Wrong Email!')

用户可以填写'email',不需要填写'email'字段。

我该怎么办?

【问题讨论】:

    标签: django python-2.7 django-forms django-1.4


    【解决方案1】:

    如果你有一个clean_field,无论你是否填写它都会被调用,因为这是由django的full_clean内部调用的。

    如果提供了一些电子邮件,您似乎只想进行自定义验证。所以,你可以这样做:

    def clean_email(self):
        email = self.cleaned_data['email']
        #If email was provided then only do validation
        if email:
            try:
                User.objects.get(email=self.cleaned_data['email'])
            except ObjectDoesNotExist:
                return email
            else:
                raise forms.ValidationError('Wrong Email!')
        return email
    

    【讨论】:

      猜你喜欢
      • 2011-06-02
      • 2019-06-14
      • 1970-01-01
      • 2013-02-01
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      • 2016-01-05
      • 2015-07-22
      相关资源
      最近更新 更多