I was trying to integrate django’s user model with my application. I had extended the user with extra data in a UserProfile class, and had made a view require login. The web page was successfully redirected to the login page when visited for the first time, but upon logging in the user was not redirected to the original page. The user was redirected to the /accounts/profile page.

It was because I had not noticed that you had to add something to the login template — you need to add a hidden field called “next” to your login form. Once I added that, and changed the form action to “./?next={{ next }}” it started working correctly.

The documentation also talks about an argument called “redirect_field_name” to the “login_required” decorator, for example:

@login_required(redirect_field_name='redirect_to')

but I couldn’t get it to work. I think the purpose of this is so you can rename “next” to some other name, but I’m not even sure of that. Does it rename the “next” of the passed context? Probably not. Does it rename the “next” hidden field in the form? Probably. But I couldn’t get it to work, so I wonder if my assumptions are correct.

So, to get authentication to work (and redirect you back to the page you asked for after you’ve logged in), you need to:

  • add a login_required decorator to a view
  • add a login template under project/templates/registration/login.html
  • put a hidden field in the login template called “next”
  • add an entry to the urls.py file for accounts/login

Optionally, you can

  • make your own login view, in which case you can put your login template anywhere you wish (rather than /registration/login.html)
  • in settings.html, set LOGIN_URL and LOGIN_REDIRECT_URL to point to your own login view.