1👍
✅
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
1👍
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():
Source:stackexchange.com