I have a custom user class for django because I needed to use email addresses instead of usernames, not sure if that is relevant for the question but I wanted to add that just in case. I am trying to redirect a user to their dashboard after successful login, however, when I attempt to call the redirect via URL, I then seem to lose the ability to access the logged in user data via request.user. How can I redirect the page from login to dashboard and maintain session data for the user between the two views? The django docs for sessions and the authentication system seem to suggest that you can use session anywhere and the data will be available if the login method was called for the user (a reference to the session stored in a cookie maybe?) but when I attempt to make calls to data in the session.user
object, there is no data there and if I wanted to do something like, say hi request.user.first_name
, there is currently not any data like that available to call.
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^create$', views.user_create),
url(r'^login', views.user_login),
url(r'^dashboard', views.display_dashboard)
]
views.py
from django.shortcuts import render, HttpResponse, redirect
from forms import RegisterForm, LoginForm
from django.contrib.auth import get_user_model, authenticate, login
# Create your views here.
def user_create(request):
if request.method == "POST":
get_user_model().object.create_user(request.POST['email_address'], request.POST['password'],
request.POST['first_name'], request.POST['last_name'],
request.POST['language'])
return render(request, 'UserHandler/user_create.html', {'form': RegisterForm})
def user_login(request):
if request.method == "POST":
user = authenticate(email_address=request.POST['email_address'], password=request.POST['password'])
if user is not None:
login(request, user)
return redirect('user/dashboard')
else:
return HttpResponse("<h3>Login Failure</h3>")
else:
return render(request, 'UserHandler/login.html', {'form': LoginForm})
def display_dashboard(request):
if request.user.is_authenticated():
return render(request, 'UserHandler/auth_dashboard.html', {'user_first_name': request.user.first_name})
else:
return render(request, 'UserHandler/login.html', {'form': LoginForm})
auth_dashboard.html
{% extends 'UserHandler/base_site.html' %}
{% block content %}
Hi {{ user_first_name }} here is your dashboard!
{% endblock %}
backends.py
from django.contrib.auth.hashers import check_password
from models import AuthLookup
class AuthLookupBackend(object):
def authenticate(self, email_address=None, password=None):
user = AuthLookup.object.get(email_address=email_address)
if user is not None:
try:
if check_password(password, user.password):
return user
else:
return None
except user.DoesNotExist:
return None
def get_user(self, user_id):
try:
user = AuthLookup.objects.get(pk=user_id)
return user
except AuthLookup.DoesNotExist:
return None
Custom user model and usermanage portion of models.py
class AuthLookup(AbstractBaseUser, PermissionsMixin):
email_address = models.EmailField(unique=True)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
# Remove the is_staff, is_superuser when done using the development database
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
user_identifier = models.UUIDField(null=False, max_length=36, default=uuid.uuid4)
language = models.CharField(max_length=6, default='US_EN')
user_added = models.DateTimeField(default='1970-01-01 00:00:00')
object = AuthManager()
USERNAME_FIELD = 'email_address'
REQUIRED_FIELDS = ['first_name', 'last_name', 'language']
def get_short_name(self):
return self.email_address
class AuthManager(BaseUserManager):
def create_superuser(self, email_address, password, first_name, last_name, language):
email_address = self.normalize_email(email_address)
superuser = AuthLookup()
superuser.email_address = email_address
superuser.set_password(password)
superuser.first_name = first_name
superuser.last_name = last_name
superuser.language = language
superuser.is_superuser = True
superuser.is_staff = True
superuser.save(using=self._db)
return superuser
def create_user(self, email_address, password, first_name, last_name, language):
email_address = self.normalize_email(email_address)
user = AuthLookup()
user.email_address = email_address
user.set_password(password)
user.first_name = first_name
user.last_name = last_name
user.language = language
user.is_staff = False
user.is_superuser = False
user.save(using=self._db)
return user
When I use this code, after login I get:
TRACEBACK
File "/home/dev/.local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/home/dev/.local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/dev/.local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/dev/DjangoProjects/myProj/UserHandler/views.py" in display_dashboard
26. if request.user.is_authenticated():
File "/home/dev/.local/lib/python2.7/site-packages/django/utils/functional.py" in inner
234. self._setup()
File "/home/dev/.local/lib/python2.7/site-packages/django/utils/functional.py" in _setup
380. self._wrapped = self._setupfunc()
File "/home/dev/.local/lib/python2.7/site-packages/django/contrib/auth/middleware.py" in <lambda>
24. request.user = SimpleLazyObject(lambda: get_user(request))
File "/home/dev/.local/lib/python2.7/site-packages/django/contrib/auth/middleware.py" in get_user
12. request._cached_user = auth.get_user(request)
File "/home/dev/.local/lib/python2.7/site-packages/django/contrib/auth/__init__.py" in get_user
187. user = backend.get_user(user_id)
File "/home/dev/DjangoProjects/myProj/UserHandler/backends.py" in get_user
21. user = AuthLookup.objects.get(pk=user_id)
Exception Type: AttributeError at /user/dashboard
Exception Value: type object 'AuthLookup' has no attribute 'objects'
However, I dont call the redirect as a test and instead do the call
if request.user.is_authenticated():
return HttpResponse(request.user.first_name)
in the place of the redirect, the if statement evaluates True
and I get a page showing the logged in user's first name
Thanks in advance for your help.
I don't really know what any of this question has to do with sessions.
You are getting that error because you have a typo in your AuthLookup model; you define object
rather than objects
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments