Reputation: 925
I have this form class :
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
Although in init I set self.notvalidate value to either True(if was given) or False inside the body of MyForm I'm getting name 'notvalidate' is not defined
(or if I check for self.notvalidate - name 'self' is not defined
). What is wrong ?
Upvotes: 0
Views: 605
Reputation: 32532
Move the if not notvalidate
into the clean_email
method, and reference it using 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
Also, you may want to rename the flag to should_validate_email
and lose the negation.
Upvotes: 2
Reputation: 88757
What are you trying to achieve is changing the class level attribute clean_email
but you want to do that using instance attribute self.notvalidate
, so you are doing contradictory things here. Simplest way to not validate would be to check in clean_email and return e.g
def clean_email(self):
if self.notvalidate:
return
....
But if due to some mysterious reason you do not want clean_mail method to be existing in the class at all, you need to create a class using metaclass or simpler way would be to call a function to create class e.g.
def createFormClass(validate):
class MyClass(object):
if validate:
def clean_email(self):
pass
return MyClass
MyClassValidated = createFormClass(True)
MyClassNotValidated = createFormClass(False)
Though I will strongly suggest NOT to do this.
Upvotes: 1