views:

47

answers:

3

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 ?

+1  A: 

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.

sdolan
why would it not work outside ?
crivateos
If you declare it outside it's a class level statement, so you won't have access the instances' `self` property, and thus can't access `self.notvalidate`.
sdolan
nope, that's not it. Still 'not defined' :/
crivateos
http://docs.python.org/tutorial/classes.html
skyl
+1  A: 

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.

Anurag Uniyal
I'm not sure why it stated 'is not defined' without this return, but now it works.
crivateos
The return has nothing to do with it. The `self.notvalidate` reference within the instance method `clean_email` is what fixed it.
sdolan
A: 

Change notvalidate to self.notvalidate.

unutbu