Question

I have a signal named user_logged_in that is dispatched when the user logs in. When the signal is received by post_user_logged_in and the user has a session variable named do_stuff set, I want to run do_stuff(), delete the session variable, and then add a new did_stuff variable to the template context so I can show a message and take other client-side action. The signal passes the request object as a parameter.

How can I modify the request object to include my new variable in the template context? I tried the below after some Googling but did_stuff remained blank in the template. I also considered using a custom message but that feels incorrect.

from django.dispatch import receiver
from django.template import RequestContext
from allauth.account.signals import user_logged_in
from myproject import do_stuff 


@receiver(user_logged_in)
def post_user_logged_in(sender, request, user, **kwargs):
    if 'do_stuff' in request.session:
        del request.session['do_stuff']
        do_stuff()
        request.context = RequestContext(request)
        request.context['did_stuff'] = True
Was it helpful?

Solution

The context is not an attribute of the request - in fact it is entirely separate from it (*) - so this approach is fundamentally mistaken. Apart from anything else, there is no single "context" - a view may render none, one, or many templates as part of the response, and each template has its own context.

I'm not sure why you can't just put your did_stuff into the session though. Or, if it needs to be transitory, just add it to the request itself, and check that in the template.

Another possibility would be to get the view to return a TemplateResponse, and write a middleware class that defines a process_template_response method to change the context_data.

(*) although the request can be an item in the context, which happens automatically if you use RequestContext and the request context_processor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top