2017-03-04 44 views
0

我有Django的自定義用戶類,因爲我需要使用電子郵件地址而不是用戶名,不知道這是相關的問題,但我想補充一點,以防萬一。我試圖在成功登錄後將用戶重定向到他們的儀表板,但是,當我嘗試通過URL調用重定向時,我似乎失去了通過request.user訪問登錄用戶數據的能力。如何將頁面從登錄重定向到儀表板並在兩個視圖之間維護用戶的會話數據?會話和身份驗證系統的django文檔似乎建議您可以在任何地方使用會話,並且如果爲用戶調用登錄方法(存儲在cookie中的會話的引用可能是?),那麼數據將可用,但是當我嘗試使在session.user對象數據呼叫,沒有數據存在,如果我想要做這樣的事情,說你好request.user.first_name,目前還沒有這樣的可調用的任何數據。Django的1.10:訪問會話數據後重定向

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的usermanage部分

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和我得到顯示已登錄用戶的名字頁面

在此先感謝您的幫助。

+0

請註明您'UserHandler/backends.py'和'AuthLookup'模型.. –

回答

1

我真的不知道任何對這個問題的有會話執行。

你得到這個錯誤,因爲你有你的AuthLookup模型中的錯字;您定義了object而不是objects

+0

它沒有有什麼用會話。很好找,謝謝 – xec86