Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django LOGIN_REDIRECT_URL with dynamic value

I'm trying to redirect a user to a url containing his username (like http://domain/username/), and trying to figure out how to do this. I'm using django.contrib.auth for my user management, so I've tried using LOGIN_REDIRECT_URL in the settings:

LOGIN_REDIRECT_URL = '/%s/' % request.user.username # <--- fail..

but it only seems to accept fixed strings, rather than something that'll be determined after the user is logged in. How can I still accomplish this?

like image 883
sa125 Avatar asked Oct 22 '09 16:10

sa125


3 Answers

With the class-based django.contrib.auth.views.LoginView, you can now simply override get_success_url:

urls.py:

url(r'^login$', MyLoginView.as_view(), name='login'),
url(r'^users/(?P<username>[a-zA-Z0-9]+)$', MyAccountView.as_view(), name='my_account'),

views.py

class MyLoginView(LoginView):

    def get_success_url(self):
        return reverse('my_account', args=[self.request.user.username])
like image 192
Flash Avatar answered Oct 20 '22 02:10

Flash


Wrap the auth view in your own custom view and redirect to wherever you want if authentication succeeded.

from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.urlresolvers import reverse

def login(request):
    template_response = auth.views.login(request)

    if isinstance(template_response, HttpResponseRedirect) and template_response.url == '/accounts/profile/':
        return HttpResponseRedirect(reverse('user', args=(request.user.username,)))


    return template_response

Another alternative is to use the query param next to indicate where to redirect to after the login.

<a href="{% url 'login' %}?next={{ request.path }}">sign in</a>
like image 37
tonyctl Avatar answered Oct 20 '22 03:10

tonyctl


A solution, is to redirect to a static route like '/userpage/' and have that redirect to the final dynamic page.

But I think the real solution is to make a new view that does what you really want.

from django.contrib.auth import authenticate, login
from django.http import HttpResponseRedirect

def my_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            HttpResponseRedirect('/%s/'%username) 
        else:
            # Return a 'disabled account' error message
    else:
        # Return an 'invalid login' error message.

http://docs.djangoproject.com/en/dev/topics/auth/#authentication-in-web-requests

for more information about rewriting the view. This is how the docs say to override this kind of thing.

like image 19
emeryc Avatar answered Oct 20 '22 04:10

emeryc