views:

284

answers:

1

Hi - 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?

+3  A: 

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.

emeryc
I prefer the first suggestion of redirecting from the static /userpage/. That way, you can still use the login view from `django.contrib.auth.views`, which might be more robust than a hand rolled view.
Alasdair
as I'm trying to simplify urls and minimize redirects, your solution seems like the way to go. thanks!
sa125