0

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 ?

2 Answers2

0

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.

AKX
  • 152,115
  • 15
  • 115
  • 172
  • can you give an example please @AKX – ash Feb 22 '22 at 10:18
  • Or can you please write, How I can render a form in Context processor whenever I am trying to submit it? Or on refresh, it is submitting again and again. Can I render a message from a context processor? – ash Feb 22 '22 at 10:23
  • 1
    @ash You can return a form object from a context processor if you need to. I wouldn't use a context processor to manipulate request messages, it sounds like quite the hairy side effect. – AKX Feb 22 '22 at 10:39
  • i am creating a footer subscribe form – ash Feb 22 '22 at 10:42
  • so and i am new to django – ash Feb 22 '22 at 10:42
  • 1
    Right. You can use a template tag or context processor to render one, but the comments here aren't the right place for questions. Ask a question detailing your particular problem. – AKX Feb 22 '22 at 10:43
  • remember i asked alredy you commented too – ash Feb 22 '22 at 10:43
-1

EDIT: The above answer assumed something else so I've deleted and replaced with an elaboration of why returning redirect doesn't work in case you want to understand

context = {}
redirect = redirect('login')
context.update(redirect)

This should cause the same error you're getting. Got the idea?

Ahmed I. Elsayed
  • 2,013
  • 2
  • 17
  • 30