Reputation: 1697
I have a form where I need to check user email only if the user is not already logged in. I know I can check the email in my view but for this form I would prefer to check the email in my form.
with the code below, I'm getting error: global name 'request' is not defined
inside the clean_email even though the request
is imported.
class MyForm(forms.ModelForm):
def __init__(self, request, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
def clean_email(self):
if not request.user.is_authenticated():
email = self.cleaned_data['email']
if User.objects.filter(email=email).exists():
raise forms.ValidationError(u'Email "%s" is already in use!' % email)
return email
Upvotes: 2
Views: 6702
Reputation: 308839
In the clean_email
method, you do not automatically have access to the arguments passed to the __init__
method.
You need to store the request
in self.request
in the __init__
method, then you can access it in the clean_email
method.
class MyForm(forms.ModelForm):
def __init__(self, request, *args, **kwargs):
self.request = request
super(MyForm, self).__init__(*args, **kwargs)
def clean_email(self):
if not self.request.user.is_authenticated():
Upvotes: 1
Reputation: 5322
the request object doesn't go to the form.
But you can easily change the constructor of your form class to receive a user object:
def __init__(self, user, *args, **kwargs):
self.user = user
super(MyForm, self).__init__(*args, **kwargs)
And then you can check if the user is authenticated later on:
def clean_email(self):
if not self.user.is_authenticated():
If you really need the whole request object, you just need to add the self, otherwise it tries to access a global variable called request. i.e:
if not self.request.user.is_authenticated():
And of course, assign the object variable, so it can be accessible from any method of the class:
self.request = request
Upvotes: 2