I created a login form for my first Django application. An error message in the case of entering incorrect data appears on a blank page. Can you please tell how you can make this message displayed directly next to the form on the same page (index.html)?

Here is the corresponding presentation function:

def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect('/friends_plans/users/', {'username': username, }) else: return HttpResponse("Your account is disabled") else: print "Invalid login details: {0}, {1}".format(username, password) return HttpResponse("Invalid login details supplied.") else: return render(request, 'friends_plans/index.html', {}) 

And this is the template index.html:

 {% load staticfiles %} <html > <head > <title> Friends' Plans </title> <meta charset ="utf -8" /> <link rel="stylesheet" href="{% static 'css/friends_plans.css' %}"> </head > <body > <div id ="container"> <div id ="header"> <ul id ="menu"> <span><a id="firstbutton" href ="" >Friends' Plans</a> </span> <span><a id="helpbutton" href ="" >HELP</a></span> </ul> </div> <div id ="left"> <form id="login_form" method="post" action=""> {% csrf_token %} Username: <input type ="text" name ="username" value="" size="50" /> <br /> Password: <input type ="password" name ="password" value="" size="50"/> <br /> <input type ="submit" value="submit" /> </form> {% if user.is_authenticated %} <a href="/friends_plans/logout/">Logout</a> {% else %} <a href="/friends_plans/register/">Register here</a><br /> {% endif %} </div> <div id ="right"> <h1 id="welcome">Welcome to Friends' Plans</h1> <img class="cat" src={% static 'images/cat4.jpg' %} /> <img class="cat" src={% static 'images/cat2.jpg' %} /> <img class="cat" src={% static 'images/cat3.jpg' %} /> <img class="cat" src={% static 'images/cat6.jpg' %} /> <img class="cat" src={% static 'images/cat5.jpg' %} /> <img class="cat" src={% static 'images/cat1.jpg' %} /> </div> <div id ="footer"> Copyright </div> </div> </body> </html> 

I had an idea to assign the error=False variable and change its value to error=True if the password / login was entered incorrectly, but when I sent the form, an error message related to csrf_token appeared, although {% csrf_token %} present in the template.

  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

It is best to use the Django Forms API . Define the form in the forms.py file

 from django import forms class LoginForm(forms.Form): username = forms.CharField(label=u'Имя пользователя') password = forms.CharField(label=u'Пароль') next = forms.CharField(widget=forms.HiddenInput(), required=False) 

Use it in a view

 from .forms import LoginForm def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user and user.is_active: login(request, user) return HttpResponseRedirect('/friends_plans/users/', {'username': username, }) else: form.add_error(None, 'Unknown or disabled account') return render(request, 'friends_plans/index.html', {'form': form}) else: return render(request, 'friends_plans/index.html', {'form': form}) else: return render(request, 'friends_plans/index.html', {'form': LoginForm()}) 

and in the pattern

 ... {% for error in form.non_field_errors %} <span class="error-message">{{ error }}</span> {% endfor %} <form id="login_form" method="post" action=""> {% csrf_token %} {% form.as_p %} </form> ... 

Or, if you don't want to make big changes to the existing code, then use the Django messages framework

view.py

 from django.contrib import messages def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect('/friends_plans/users/', {'username': username, }) else: messages.error(request, 'Your account is disabled') return render(request, 'friends_plans/index.html', {}) else: print "Invalid login details: {0}, {1}".format(username, password) messages.error(request, 'Invalid login details supplied.') return render(request, 'friends_plans/index.html', {}) else: return render(request, 'friends_plans/index.html', {}) 

index.html

 ... {% for message in messages %} <div class="message {{ message.tags }}"> {{ message }} </div> {% endfor %} <form id="login_form" method="post" action=""> ... 
  • Thank you very much, Sergey! It turned out with the use of messages. - Anastasia Novikova