Question

I want to allow the users to go to their user page by default (like: mywebsite.com/userpage) when they use the login form.

Also if they go to some other password protected page on the web site redirect them to the login page first and once authenticated get them back to the original page they were trying to access.

This is what I have so far for the login function:

views.py

def user_login(request):
    if request.method == 'POST': 
        form = AuthenticationForm(request.POST)
        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)
                # Redirect to a successpage
                if request.POST['next']:
                    return HttpResponseRedirect(request.POST['next'])
                else:    
                    return HttpResponseRedirect("/" + username + "/")
            else:
                errors = 'This account has been disabeled.'
        else:
            # Return an 'invalid login' error message.
            errors = 'There is a problem with the user name and/or the password. Please try again.'
    else:
        form = AuthenticationForm()
    return render_to_response("registration/my_login.html", locals(), context_instance=RequestContext(request))

urls.py

urlpatterns = patterns('',
                       url(r'^login/$', user_login,),

my_login.html

<form action="." method="post" >{% csrf_token %}
    {{errors}}
    {{ form.as_p }}
    <p class="submit"><button type="submit" name="login_user_button" value="Login">Log in</button></p>
    <input type="hidden" name="next" value="{{ next }}">
    </form>

My problem is that I don't know how to get the values of the "next" variable so I can use it in my user_login function for the redirect.

As you can see I tried to get it with request.POST['next'] but comes with an empty string so for some reason no value gets signed to the "next" variable.

Any ideas?

Was it helpful?

Solution

My recommendation - don't bother screwing around with the login function. You're just reinventing the wheel. Instead, use the login view that comes with the django.auth module, and have that send users to an interstitial page (with a URL defined in settings.LOGIN_REDIRECT_URL) that redirects them where they need to go.

This interstitial view could be something as simple as the following:

@login_required
def index(request):
    return redirect('user-page', request.user.username)

Note that I've changed that redirect to use a named view. You don't want weird stuff to happen if a user gives himself a username that coincides with a site url!

Also note the login_required decorator. This automatically gives you the login page redirect you require.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top