Django AttributeError: 'WSGIRequest' object has no attribute 'user'

I have problem after upgrade Django 1.4 to 1.5
and when I have in settings:
DEBUG = False
so code:

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

Give me error:
AttributeError: 'WSGIRequest' object has no attribute 'user'
but when I have set
DEBUG = True
so all is ok

Do you know anybody where is problem why in production mode it give me the Error?

Thanks

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',
)

Upvotes: 2

Views: 2497

Answers (3)

karuoro
karuoro

Reputation: 571

Just put your context processor in a try...except block:

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

it might fail for some pages but will pass in others... Is it hacky, yes, but it won't bring down your site

Upvotes: 0

LukeSkyvolker
LukeSkyvolker

Reputation: 11

We had a similar issue after upgrading to Django 1.5. In our case though it was that we never set ALLOWED_HOSTS in the settings file. According to the Django 1.5 documentation the test will only be performed when DEBUG=False so the error never got triggered in our dev environments. Once set, the error disappeared.

Upvotes: 1

levi
levi

Reputation: 22697

You need to change your middleware order

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

Upvotes: 1

Related Questions