0

I'm a newbie to Django and Python. I'm learning with the Tango with Django Tutorial and I want to add some features to the tutorial login form. My issue is that I can't get the form errors to show when the login forms is taking the next parameter to redirect users after login. What is the best way to achieve this?

forms.py

from django import forms
from rango.models import Page, Category, UserProfile
from django.contrib.auth.models import User

class UserLoginForm(forms.Form):
    username = forms.CharField(help_text="Please enter a username.", required=True)
    password = forms.CharField(widget=forms.PasswordInput(), help_text="Please enter a password.", required=True)
    class Meta:
        model = User
        fields = ('username', 'password')

views.py

from django.template import RequestContext
from django.shortcuts import render_to_response
from rango.models import Category, Page
from rango.forms import CategoryForm, PageForm, UserLoginForm, UserForm, UserProfileForm
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required

def user_login(request):
    context = RequestContext(request)
    NEXT = ""
    if 'next' in request.GET:
        NEXT = request.GET['next']
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        user_login_form=UserLoginForm(request.POST)
        errors=user_login_form.errors
        if user_login_form.is_valid():
            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:
            if request.POST['next']:
                return HttpResponseRedirect(request.POST['next'])
            else:
                print errors
    else:
        user_login_form=UserLoginForm()
    return render_to_response('rango/login.html', {'NEXT': NEXT, 'user_login_form': user_login_form}, context)
3
  • can you show the templates? Commented Jun 15, 2014 at 9:36
  • {% if user_login_form.errors %} <p style="color:red">The login was unsuccessfull. Correct the errors in the form below!</p> {% endif %} <form class="form-signin" id="login_form" method="post" action="/rango/login/"> {% csrf_token %} {{ user_login_form.as_p }} <input type="hidden" name="next" value="{{ NEXT }}" /> <input type="submit" value="submit" /> </form> Commented Jun 16, 2014 at 6:45
  • add this code ^ in question, thanks Commented Jun 16, 2014 at 7:49

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes if parameter next is in the url (/rango/login/?next=/rango/add_category/) than I want to redirect the user to that url after login. It is working only if the user logs in with the correct details the first time the page is loaded, but if the user enters the wrong login data than the "print errors" gets run and page is refreshed without the next parameter in the url...So I want the next parameter in the url also if errors are printed and page is refreshed...I tried your code but is not displaying errors probably because my template is not correct. Can you show how the template should be?
@user3741904 Updated. Check answer.
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.

1 Comment

I don't know how to make it work with your suggestion. My problem is that if form is not valid than else - print errors gets run and it refreshes the page without the next parameter in the url...so if now user enters correct login details he will not be redirected to next anymore...hope is understandable what I mean..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.