I have tried to login a user after the user clicks the activation link send to the user's email. But directly using the login()
method will throw me the error 'User' object has no attribute 'backend'
. I have tried using authenticate()
method but since i need to use the password already stored in the backend, authenticate(username, password)
does not return any user.
Here is my activation view
def activate(request, uidb64, token):
try:
uid = force_text(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.save()
login(request, user)
return HttpResponse('Thank you for your email confirmation. Now you can login your account.')
else:
return HttpResponse('Activation link is invalid!')
To solve the issue of User object has no attribute backend
I used authenticate as:
username = user.username
password = user.password
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
No user is returned. Can somenone help me?
Edit: I am using Django 1.8.11 and python2.7
Traceback:
File "/home/sanip/naxa/source/fieldsight/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/sanip/naxa/source/fieldsight/onadata/apps/users/views.py" in activate
628. login(request, user)
File "/home/sanip/naxa/source/fieldsight/venv/local/lib/python2.7/site-packages/django/contrib/auth/__init__.py" in login
112. request.session[BACKEND_SESSION_KEY] = user.backend
Exception Type: AttributeError at /users/activate/NjYx/53u-911ceda96c18c2e7dce1/
Exception Value: 'User' object has no attribute 'backend'
Basically you need to provide the stock backend here directly as a variable
Try Again With This:
def activate(request, uidb64, token):
try:
uid = force_text(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.save()
user.backend = 'django.contrib.auth.backends.ModelBackend' #<-- addition
login(request, user)
return HttpResponse('Thank you for your email confirmation. Now you can login your account.')
else:
return HttpResponse('Activation link is invalid!')