简体   繁体   中英

Django - Render view on user_logged_out signal

I would like to be able to render a different logged out template when the user_logged_out signal is fired. I can catch the signal and check for my condition correctly, and I have a view with a named URL that works just fine, but I can't seem to render the view.

I've tried each of these, with both a class based and functional view, but can't get them to work. Using ipdb I can get a template to render in the console, but can't figure out the right way to return it/call the view to have it returned. Thoughts?

@receiver(user_logged_out)
def my_logged_out_signal_handler(sender, request, user, **kwargs):
    if user.has_condition:
        # tried this
        resolve(reverse('my_named_url', kwargs={'kwarg1': 'something'})).func(request, something)
        # and this
        render_to_response(resolve(reverse('my_named_url', kwargs={'kwarg1': something})).func(request, kwarg1=something).render())
        # and this
        render(MyClassView.as_view()(request, kwarg1=something))
        # and this
        return (resolve(reverse('my_named_url', kwargs={'kwarg1': something})).func(request, kwarg1=something).render())
        # and this
        return HttpResponse(resolve(reverse('my_named_url', kwargs={'kwarg1': something})).func(request, kwarg1=something).render())

A signal handler is not a view, it cannot render/return a response.

You could simply handle logic in your own view, and call or redirect to the auth logout function from there. Something like below..

from django.shortcuts import redirect

def my_logout(request):
    kwargs = {}
    if my_condition:
        kwargs['template_name'] = 'my_template.html'
        kwargs['extra_context'] = ...
    return redirect('logout', **kwargs)

Found a clever solution allowing a redirect from anywhere, if you really need to. https://djangosnippets.org/snippets/2541/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM