Django 1.10:重定向

时间:2017-03-04 07:07:14

标签: python django session redirect

我有一个django的自定义用户类,因为我需要使用电子邮件地址而不是用户名,不确定这是否与问题相关,但我想添加以防万一。我试图在成功登录后将用户重定向到他们的仪表板,但是,当我尝试通过URL调用重定向时,我似乎失去了通过request.user访问登录用户数据的能力。如何将页面从登录重定向到仪表板,并在两个视图之间维护用户的会话数据?会话和身份验证系统的django文档似乎建议你可以在任何地方使用会话,如果为用户调用登录方法,数据将可用(对cookie中存储的会话的引用可能?)但是当我尝试时要调用session.user对象中的数据,那里没有数据,如果我想做类似的事情,比如hi request.user.first_name,那么目前没有任何数据可供调用。

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

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

当我使用此代码时,登录后我得到:

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'

但是,我不会将重定向称为测试,而是进行调用

if request.user.is_authenticated():
     return HttpResponse(request.user.first_name)

在重定向的位置,if语句评估True,我得到一个显示登录用户的名字的页面

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我真的不知道这个问题与会话有什么关系。

您收到该错误是因为您的AuthLookup模型中有拼写错误;您定义object而不是objects