[Answer]-Django: Form errors with next parameter

1👍

I’m guessing you’re trying to redirect the user to a URL if the login is successful and if login unsucessful, display the form errors (correct me if I’m wrong). And this URL is in the ‘next’ parameter.

Because if you have form errors, the user wouldn’t authenticate and you don’t have to redirect, right?

def user_login(request):
    context = RequestContext(request)
    errors = None
    if 'next' in request.GET:
        NEXT = request.GET['next']
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user_login_form = UserLoginForm(request.POST)

        if user_login_form.is_valid():
            user = authenticate(username=username, password=password)

            if user:
                if user.is_active:
                    login(request, user)
                    if request.POST['next']:
                        return HttpResponseRedirect(request.POST['next'])
                    else:
                        return HttpResponseRedirect('/rango/')
                else:
                    return HttpResponse("Your Rango account is disabled.")
            else:
                return HttpResponse("Invalid login")
        else:
            errors = user_login_form.errors
            NEXT = request.POST['next']

    user_login_form=UserLoginForm()
    return render_to_response('rango/login.html', {'NEXT': NEXT, 
                              'user_login_form': user_login_form,
                              'errors': errors}, context)

Have your template show the form errors when errors is non-empty.

More:

The template could be something like,

<p>{{ errors }}</p>
<form action="/contact/" method="post">
    {{ user_login_form.as_p }}
    <input type="submit" value="Submit" />
</form>

Of course, this is a bare skeleton. Read this article for better ways to display the form and the form errors.

0👍

Make a redirect without the next parameter.

def user_login(request):
    ... 
    if form.is_valid():
        return HttpResponseRedirect('/user-profile/')
    else:
        # do something else

Above, /user-profile/ is the url of the page to which you want to redirect the user after logging in.

👤xyres

Leave a comment