python - Django Form Validation Only if User is Not Authenticated? -


i have form need check user email if user not logged in. know can check email in view form prefer check email in form.

with code below, i'm getting error: global name 'request' not defined inside clean_email though request 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" in use!' % email)             return email 

the request object doesn't go form.

but can change constructor of form class receive user object:

def __init__(self, user, *args, **kwargs):     self.user = user     super(myform, self).__init__(*args, **kwargs) 

and can check if user authenticated later on:

def clean_email(self):     if not self.user.is_authenticated(): 

if need whole request object, need add self, otherwise tries access global variable called request. i.e:

if not self.request.user.is_authenticated(): 

and of course, assign object variable, can accessible method of class:

self.request = request 

Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -