Django AttributeError:'WSGIRequest'对象没有属性'user'

时间:2015-11-02 17:07:24

标签: python django authentication

将Django 1.4升级到1.5后我遇到了问题
当我在设置中时:
DEBUG = False
所以代码:

def get_cart(request):
    """
    Returns cart for user or None if cart does not exist,
    means that user didn't add item to it.
    """
    shop_cart = None
    if request.user.is_authenticated():
        try:
            shop_cart = ShoppingCart.objects.get(customer=request.user)
        except ShoppingCart.DoesNotExist:
            pass
    else:
        cart_id = request.session.get('cart_id', None)
        try:
            shop_cart = ShoppingCart.objects.get(pk=cart_id)
        except ShoppingCart.DoesNotExist:
            pass
    return shop_cart

给我错误:
AttributeError:'WSGIRequest'对象没有属性'user'
但是当我设置了 DEBUG =真实 所以一切都好了

你知道有什么问题吗?为什么在生产模式下它会给我错误?

由于

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.middleware.http.ConditionalGetMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.contrib.messages.context_processors.messages',
    'django.core.context_processors.i18n',
    'django.core.context_processors.request',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.core.context_processors.request',
    'eshopwisepress.wp_core.context_processors.request_absolute_path',
    'eshopwisepress.wp_core.context_processors.domain',
)

3 个答案:

答案 0 :(得分:1)

您需要更改中间件订单

'django.contrib.auth.middleware.AuthenticationMiddleware'
'django.contrib.sessions.middleware.SessionMiddleware',

答案 1 :(得分:1)

升级到Django 1.5之后我们遇到了类似的问题。 在我们的例子中,我们从未在设置文件中设置ALLOWED_HOSTS。根据{{​​3}},只有当DEBUG = False时才会执行测试,因此错误永远不会在我们的开发环境中触发。设置后,错误消失。

答案 2 :(得分:0)

只需将上下文处理器放在try...except块中:

try:
    # your context processor logic
except:
    return {}

某些页面可能会失败,但其他页面会通过...是不是很hacky,是的,但是它不会破坏您的网站