窗体类初始化无效

2024-09-28 12:15:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个表格课:

class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.notvalidate = kwargs.pop('notvalidate',False)
        super(MyForm, self).__init__(*args, **kwargs)

    email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,maxlength=75)))
    (...)

    if not notvalidate:        
        def clean_email(self):
            email = self.cleaned_data.get("email")
            if email and User.objects.filter(email=email).count() > 0:
                raise forms.ValidationError(
                    _(u"Email already used."))
            return email

虽然在init我设置了自我验证值为True(如果已给定)或False(如果在MyForm的主体中得到name 'notvalidate' is not defined(或者如果我检查自我验证-name 'self' is not defined)。怎么了?在


Tags: nameselffalseifinitemaildefnot
3条回答

if not notvalidate移到clean_email方法中,并使用self.notvalidate引用它。在

    def clean_email(self):
       if not self.notvalidate:   
           email = self.cleaned_data.get("email")
           if email and User.objects.filter(email=email).count() > 0:
                raise forms.ValidationError(
                    _(u"Email already used."))
        return email

另外,您可能希望将该标志重命名为should_validate_email,并丢失否定。在

{{cd2>你想要做的事情是{cd2>你想用这个属性来实现。不验证的最简单方法是签入干净的电子邮件并返回

def clean_email(self):
    if self.notvalidate:
        return

     ....

但是,如果由于某种神秘的原因,您根本不希望clean-mail方法存在于类中,那么您需要使用元类创建一个类,或者更简单的方法是调用一个函数来创建类

^{pr2}$

但我强烈建议不要这样做。在

notvalidate更改为self.notvalidate。在

相关问题 更多 >

    热门问题