【问题标题】:If I don't want to call clean_<fieldname>() method, can I do it?如果我不想调用 clean_<fieldname>() 方法,我可以这样做吗?
【发布时间】:2013-02-01 08:12:16
【问题描述】:

Django:如果我不想调用 clean_() 方法,我可以这样做吗?

class myForm(forms.Form):
    userId = forms.CharField(max_length=30, required=False,)
    email = forms.EmailField(required=False,)

    def clean_userId(self):
        if 'userId' in self.cleaned_data:
            if not re.search(r'^\w+$', self.cleaned_data['userId']):
                raise forms.ValidationError('Invalid ID')
            try:
                User.objects.get(username=self.cleaned_data['userId'])
            except ObjectDoesNotExist:
                return self.cleaned_data['userId']
            raise raise forms.ValidationError('Invalid ID')
        else:
            raise raise forms.ValidationError('Invalid ID')

有时,我想使用表单验证来仅验证“电子邮件”字段。

如下:

>>> form = myForm({'email':'abc@com'})
>>> form.cleaned_data['email']
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'myForm' object has no attribute 'cleaned_data'
>>> print form.errors
<ul class="errorlist"><li>workers<ul class="errorlist"><li>Invalid ID</li></ul>

有办法吗?

【问题讨论】:

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


    【解决方案1】:

    你不需要定义clean_userId()或者clean_email(),只需要定义clean(),在Form的那个方法里做。

    class MyForm(forms.Form):
        # fields
    
        def clean(self):
            cleaned_data = super(MyForm, self).clean()
            email = cleaned_data.get('email')
    
            # do some validation
    
            return cleaned_data
    

    在您访问cleaned_data 之前,记得致电form.is_valid()

    【讨论】:

    • 嗯...顺便说一句,我是否必须验证“#做一些验证”部分中的所有其他字段?
    • 我可以在其他部分使用验证吗?
    • 编写你的函数来做到这一点。
    【解决方案2】:

    你可以试试这样的:

    form = myForm({'email':'abc@com'})
    try:
        form.clean_email()
    except forms.ValidationError:
        #do whatever
    else:
        #do whatever
    

    is_valid() 将在所有内容上调用 clean,因此只需调用您想要的任何 clean 方法。

    您也可以只有两种不同的表单或从另一个继承的表单,这会比 IMO 好得多。

    【讨论】:

      猜你喜欢
      • 2011-06-02
      • 2019-06-14
      • 1970-01-01
      • 2010-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-27
      相关资源
      最近更新 更多