Search code examples
pythondjangodjango-context

Django context processor throw error on redirect


I'm using the following context processor to pass context to all my pages, except when the user is not logged in which case it takes him to the login page :

from django.conf import settings
from .models import foo
from django.shortcuts import redirect


def globalVar(request):
    if not request.session.get('user_id') is None:
        return {"foo": foo}
    else:
        return redirect('login')

But the redirect causes an exception for which i didn't find a fix : ValueError: dictionary update sequence element #0 has length 0; 2 is required

Am i not looking in the right place, or is there a way to replace redirect by something else ?


Solution

  • You can't simply return a redirect from a context processor, since context processors need to return a dict of context variables.

    If you really need this functionality in a context processor, you would need to

    • define a custom exception class (that e.g. wraps the response)
    • raise such an exception from the context processor (since you can't return a non-dictionary)
    • catch the custom exception in a Django middleware, unwrap the response and return it

    (as an aside, I've written a package that does that – django-safespace)

    Instead, if you can, use the login_required decorator (or CBV mixin – see the linked documentation) to make your entire view logged-in-user only.