【问题标题】:Django: unbound method is_authenticated() must be called with AbstractBaseUser instanceDjango:必须使用 AbstractBaseUser 实例调用未绑定的方法 is_authenticated()
【发布时间】:2016-10-29 10:18:37
【问题描述】:

这个问题比较奇怪。这是一个堆栈跟踪:

Environment:


Request Method: GET
Request URL: http://localhost/en/dashboard

Django Version: 1.9.6
Python Version: 2.7.12
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'django_mongoengine',
 'django_mongoengine.mongo_auth',
 'django_mongoengine.mongo_admin.sites',
 'django_mongoengine.mongo_admin',
 'django_adyen',
 'spiral_api',
 'rest_framework',
 'rest_framework_mongoengine',
 'spiral_admin',
 'rest_framework_docs')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.locale.LocaleMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'spiral_api.middlewares.BehalfUserMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'spiral_api.middlewares.AuthHeaderMiddleware')



Traceback:

File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  235.                 response = middleware_method(request, response)

File "/code/django_app/spiral_api/middlewares.py" in process_response
  11.     def process_response(self, request, response):

File "/usr/local/lib/python2.7/site-packages/django/utils/functional.py" in inner
  204.             self._setup()

File "/usr/local/lib/python2.7/site-packages/django/utils/functional.py" in _setup
  351.         self._wrapped = self._setupfunc()

File "/code/django_app/spiral_api/middlewares.py" in get_user
  18.         user = get_user_middleware(request)

Exception Type: TypeError at /en/dashboard
Exception Value: unbound method is_authenticated() must be called with AbstractBaseUser instance as first argument (got nothing instead)

这是一个中间件:

from functools import partial

from django.contrib.auth.middleware import get_user as get_user_middleware
from django.contrib.auth.models import AbstractBaseUser
from django.utils.functional import SimpleLazyObject

from spiral_api.models import SpiralUserProfile


class AuthHeaderMiddleware(object):
    def process_response(self, request, response):
        response['is_login'] = int(request.user.is_active) if hasattr(request, 'user') else 0
        return response


class BehalfUserMiddleware(object):
    def get_user(self, request):
        user = get_user_middleware(request)
        if user.is_authenticated():
            profile = SpiralUserProfile.objects.get(user=user)
            return profile.behalf or user
        else:
            return user

    def process_request(self, request):
        assert hasattr(request, 'session'), (
            "The Django authentication middleware requires session middleware "
            "to be installed. Edit your MIDDLEWARE_CLASSES setting to insert "
            "'django.contrib.sessions.middleware.SessionMiddleware' before "
            "'django.contrib.auth.middleware.AuthenticationMiddleware'."
        )
        request.user = SimpleLazyObject(partial(self.get_user, request))
        request.behalf = SimpleLazyObject(lambda: get_user_middleware(request))

遗憾的是,项目不是我的。从异常中您可以看到它指向 get_user_middleware() 函数。我尝试在其中添加print,也添加为sys.exit(),没有任何效果.. 似乎它甚至没有达到那个功能。设置中的中间件设置如下所示:

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
     # 'django.contrib.auth.middleware.AuthenticationMiddleware',
     'spiral_api.middlewares.BehalfUserMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
     'spiral_api.middlewares.AuthHeaderMiddleware'
)

还有一个模型SpiralUserProfile 有一个字段behalf 引用模型User。我完全不明白为什么异常会在解释器甚至没有出现的地方显示错误?如何解决这个问题?

requirements.txt 的版本:

nose==1.3.7
pinocchio==0.4.2
django_nose==1.4.4
bjoern==1.4.3
amqp==1.4.9
anyjson==0.3.3
apiclient==1.0.3
billiard==3.3.0.23
blinker==1.4
build==1.0.2
celery==3.1.23
Django==1.9.6
django-bootstrap3==7.0.1
django-crispy-forms==1.6.0
django-fanout==1.1.1
django-filter==0.13.0
git+https://github.com/MongoEngine/django-mongoengine
django-redis==4.4.3
django-rest-framework-mongoengine==3.3.0
djangorestframework==3.3.3
drfdocs==0.0.9
EasyProcess==0.2.2
fanout==1.2.0
git+http://github.com/google/google-api-python-client/
gunicorn==19.3.0
httplib2==0.9.2
kombu==3.0.35
mongodbforms==0.3
mongoengine==0.10.6
nltk==3.2.1
oauth2==1.9.0.post1
oauth2client==2.1.0
oauthlib==1.1.2
Pillow==3.2.0
psycopg2==2.6
pubcontrol==2.2.7
pyasn1==0.1.9
pyasn1-modules==0.0.8
PyInvoice==0.1.7
PyJWT==1.4.0
pymongo==3.2.2
python-openid==2.2.5
pytz==2016.4
PyVirtualDisplay==0.2
qrcode==5.3
qrplatba==0.3.4
redis==2.10.5
reportlab==3.3.0
requests==2.10.0
requests-oauthlib==0.6.1
rsa==3.4.2
selenium==2.53.2
simplejson==3.8.2
six==1.10.0
uritemplate==0.6
urllib3==1.15.1
xvfbwrapper==0.2.8
zope.dottedname==4.1.0
pyPdf

【问题讨论】:

  • 这是完整的堆栈跟踪吗?

标签: django python-2.7 django-rest-framework


【解决方案1】:

我不确定它是如何工作的,但我知道你为什么会收到这个错误。在django-mongoengine/mongo_auth/models.py 我看到了这个:

class BaseUser(object):

    is_anonymous = AbstractBaseUser.is_anonymous
    is_authenticated = AbstractBaseUser.is_authenticated

class User(BaseUser, document.Document):
    ...

这似乎是错误的根源。

您可以通过修改该库来使其工作,以便 User 类直接实现这些方法:

class User(document.Document):
    ...
    def is_anonymous(self):
        """
        Always returns False. This is a way of comparing User objects to
        anonymous users.
        """
        return False

    def is_authenticated(self):
        """
        Always return True. This is a way to tell if the user has been
        authenticated in templates.
        """
        return True

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-15
  • 2014-09-10
  • 1970-01-01
  • 2014-12-10
  • 2011-05-27
  • 2018-02-18
相关资源
最近更新 更多