2013-03-04 5 views
0

표준 유추 모델에 추가 필드를 추가하기 위해 AbstractUser 모델을 만들었습니다.로그인시 장고 AbstractUser 오류

나는 모든 것이 올바르게 설정되어 생각하지만, 내가 로그인 할 때이 오류가 얻을 : 여기

unbound method save() must be called with UserProfile instance as first argument (got nothing instead) 

를 내 계정/models.py 내 설정에서

from django.db import models 
from django.conf import settings 
from django.contrib.auth.models import UserManager, AbstractUser 


class UserProfile(AbstractUser): 
    mobile = models.CharField(max_length=20, blank=True) 
    homephone = models.CharField(max_length=20, blank=True) 
    updated = models.DateTimeField(blank=True, null=True)  

    objects = UserManager() 

을 내가 가진 :

AUTH_USER_MODEL = 'accounts.UserProfile' 

내 인증 미들웨어 :

외부 사용자의 로그인에 대한 617,451,515,
from django.conf import settings 
from django.contrib.auth import authenticate, login 
from django.contrib.auth.models import User 
from accounts.models import UserProfile 


#Authentication Middleware using a external cookie named AUTHENTICATION 
class CookieMiddleware(object): 

    def process_request(self, request): 
     #if not hasattr(request, 'userprofile'): 
     # raise ImproperlyConfigured() 
     if "AUTHENTICATION" not in request.COOKIES: 
      #Cookie not found - do nothing 
      return 

     #Token found - first check if the user is allready is logged in 
     if request.user.is_authenticated(): 
      return 

     #Not logged in, then send to RemoteUserBackend.py  
     token = request.COOKIES["AUTHENTICATION"] 

     #Return if the cookie length is 0 
     if len(token) == 0: 
      return 

     UserProfile = authenticate(token=token) 
     request.UserProfile = UserProfile 

     if request.UserProfile: 
      login(request, request.UserProfile) 

내 RemoteUserBackend.py :

from django.conf import settings 
from django.contrib.auth import authenticate, login 
from django.contrib.auth.models import User 
from base64 import b64decode 
from hashlib import sha1 
from urllib import unquote 
from sitetasks import tasks 
from accounts.models import UserProfile 


class Backend(object): 
     def authenticate(self, username=None, password=None, token=None): 

      #Unescape token 
      unescaped_token = unquote(token) 

      #Decode token 
      decoded_token = unescaped_token.decode('base64') 

      #Split the token into tree variable 
      secret, hashstring, userID = decoded_token.split('-', 2) 

      #Secret needs to bee in lower to match shared secret 
      secret_lower = secret.lower() 

      #Make string of SHARED_SECRET, hashstring, userID 
      check_string = "%s%s%s" % (settings.SHARED_SECRET, hashstring, userID) 

      #sha1 the string 
      sha1_check_string = sha1(check_string) 

      #Check if the SHARED_SECRET is matching cookie secret 
      cookie_valid = sha1_check_string.hexdigest() == secret_lower 

      if cookie_valid: 
       try: 
        userprofile = UserProfile.objects.get(username=userID) 

        #The user exist, then update the user 

        #Make celery worker update user asynchronous 
        tasks.user_update.delay(user_id=userID) 

       except UserProfile.DoesNotExist: 
        # Create a new user 

        userprofile = UserProfile(username=userID) 
        userprofile.is_staff = False 
        userprofile.is_superuser = False 



        userprofile.save() #Save the user 

        #Make celery worker update user asynchronous 
        tasks.user_update.delay(user_id=userID) 


       return UserProfile 
      return None 

     def get_user(self, user_id): 
      try: 
       return UserProfile.objects.get(pk=user_id) 
      except UserProfile.DoesNotExist: 
       return None 

내가 오류에 대한 추적은 이것이다 :

Request Method: GET 
Request URL: http://mydomain.com/ 

Django Version: 1.6.dev20130302084542 
Python Version: 2.7.3 
Installed Applications: 
('django.contrib.admin', 
'django.contrib.admindocs', 
'django.contrib.auth', 
'django.contrib.contenttypes', 
'django.contrib.sessions', 
'django.contrib.messages', 
'django.contrib.staticfiles', 
'django.contrib.sites', 
'django.contrib.flatpages', 
'south', 
'djcelery', 
'gunicorn', 
'sorl.thumbnail', 
'template_utils', 
'compressor', 
'tagging', 
'ckeditor', 
'debug_toolbar', 
'mptt', 
'accounts', 
) 
Installed Middleware: 
('django.contrib.sessions.middleware.SessionMiddleware', 
'django.middleware.locale.LocaleMiddleware', 
'django.middleware.common.CommonMiddleware', 
'django.middleware.csrf.CsrfViewMiddleware', 
'django.contrib.auth.middleware.AuthenticationMiddleware', 
'django.contrib.messages.middleware.MessageMiddleware', 
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', 
'django.middleware.clickjacking.XFrameOptionsMiddleware', 
'myproj.CookieMiddleware.CookieMiddleware') 


Traceback: 
File "/home/USER/.virtualenvs/SITE/downloads/django-trunk/django/core/handlers/base.py" in get_response 
    82.      response = middleware_method(request) 
File "/home/USER/.virtualenvs/SITE/myproj/myproj/CookieMiddleware.py" in process_request 
    35.    login(request, request.UserProfile) 
File "/home/USER/.virtualenvs/SITE/downloads/django-trunk/django/contrib/auth/__init__.py" in login 
    86.  user_logged_in.send(sender=user.__class__, request=request, user=user) 
File "/home/USER/.virtualenvs/SITE/downloads/django-trunk/django/dispatch/dispatcher.py" in send 
    182.    response = receiver(signal=self, sender=sender, **named) 
File "/home/USER/.virtualenvs/SITE/downloads/django-trunk/django/contrib/auth/models.py" in update_last_login 
    31.  user.save(update_fields=['last_login']) 

Exception Type: TypeError at/
Exception Value: unbound method save() must be called with UserProfile instance as first argument (got nothing instead) 

사람은 임 잘못 여기서 뭐하는 참조하십시오?

답변

0

백엔드 authenticate() 메서드는 userprofile (사용자가 속한 클래스의 인스턴스) 대신 (클래스)을 반환합니다.

미들웨어에 실제로 잘못된 것은 없지만, 일반적인 파이썬 중 하나 인 동일한 명명 규칙을 유지하고 request.UserProfile 대신 request.userprofile을 참조하면 더 명확합니다.

+0

트릭을하는 것처럼 보입니다! 고맙습니다! –