The "next" parameter, redirect, django.contrib.auth.login


I'm trying to redirect users to custom url "/gallery/(username)/" after successfully logging in. It currently redirects to the default "/account/profile/" url While I know what I can override the redirect url in my, my url is dynamic thus it will not work.

Documentation states that I need to use the "next" parameter and context processors. I have the {{next}} in my template, but I'm confused on how to actually pass the "/gallery/(username)". Any help would be greatly appreciated.

p.s: I'm trying to steer away from writing my own login view.

8/24/2018 11:01:39 PM

Accepted Answer

I confess I usually use 2 redirects in order to get something like this to work.

First, Make your own registration/login.html page. You can copy-and-paste the html example in this section of the authentication docs to make the process a little easier. Instead of using the dynamic '{{ next }} variable from the context, however, hardwire the value of next to go to a generic landing view of logged-in users

<input type="submit" value="login" />
<input type="hidden" name="next" value="/gallery/" />

Then, in the view that you map to the /gallery/ URL, extract the User object from the request (since the user will now be logged in, especially if the gallery view is wrapped in a @permission_required or @login_required decorator. Use that view to redirect to the appropriate user-specific gallery page:

def gallery(request):
    url = '/gallery/%s/' % request.user.username
    return HttpResponseRedirect(url)
8/9/2010 4:50:57 PM

Django's login view django.contrib.auth.views.login accepts a dictionary named extra_context. The values in the dictionary are directly passed to the template. So you can use that to set the next parameter. Once that is done, you can set a hidden field with name next and value {{ next }} so that it gets rendered in the template.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow