Pedro Assunção

[Django] Dynamic redirection after login

Here’s how to redirect to the login page in django, making it go to a certain view (by name) after a successful login:

login_url = '%s?next=%s' % (reverse('acct_login'), reverse('jumplog_index'))
return HttpResponseRedirect(login_url)

Notes:

  • acct_login is django’s view name for the login page (double check this, as it might change in future django versions);
  • jumplog_index is the target view where I want the user to go after successfully logging in.

UPDATE: An alternative, much more awesome, is to use the @login_required decorator on the view you want login to be required. Like so:

@login_required
def index(request):
   # Your code here

The decorator can be imported from this module:

from django.contrib.auth.decorators import login_required

I guess the first dirtier method can be used when you want to do something more custom, like sending some data to the login view, or something like that :)

Thanks for the tip, Steve :)

Related:

  1. Django: Reverse HTTP redirect with parameters Here’s how to, from a view, redirect to another URL...
  2. Django in AppEngine It’s as easy as following this article: http://code.google.com/appengine/articles/django.html. A couple...


Categorised as: code snipplets, software development, tips


4 Comments

  1. Steve says:

    Ha, thanks.

    Not a genius, that’s all down to the Django guys. But yeh, your method would come in handy if you need to do some more custom stuff. The acct_login tip is handy :)

  2. Steve says:

    Couldn’t you just use the @login_required decorator?

    If I’m not mistaken, this handles all the ?next jiggery-pokery for you.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>