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
Post a Comment