Django登录表单错误消息

时间:2016-05-09 20:21:39

标签: django django-forms django-templates django-views django-login

我已经为我的Django项目创建了登录表单,但我遇到了错误消息的问题。 这是我在views.py中的功能:

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/')
        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', {})

错误消息("提供的无效登录详细信息")出现在新的空白页面上。如果用户名或密码在同一登录页面(index.html)上不正确,您能否告诉我如何显示此消息?

这是我的模板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>

我有一个想法是设置变量error=False并更改if error=True如果form.is_valid()为False,并在模板中写{% if error %},但有关于csrf_token的错误,尽管模板中有{% csrf_token %}

2 个答案:

答案 0 :(得分:6)

在views.py中:

def login_process(request):
    try:
        user = authenticate(username = request.POST['username'],
            password = request.POST['password'])
    except KeyError:
        return render(request, 'friends_plans/index.html',{
            'login_message' : 'Fill in all fields',}) 
    if user is not None:
        #'User' and 'Pass' right
        if user.is_active:
            login(request, user)
        else:
            return render(request, 'friends_plans/index.html',{
                'login_message' : 'The user has been removed',})
    else:
        return render(request, 'friends_plans/index.html',{
            'login_message' : 'Enter the username and password correctly',})
    return HttpResponseRedirect('/friends_plans/users/')

在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="">
                <div class="add_your_styles">
                    {{ login_message }}
                </div>
                {% 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>

您可以在任何地方放置{{login message}}。它只是一个文本字符串。

答案 1 :(得分:0)

对于类似的内容,您可以使用 Django的消息框架。 在您导入中,添加行

from django.contrib import messages 

这将使消息框架可用,现在您要为此失败的登录请求添加错误消息,所以您只需要

messages.error(request, 'Invalid login credentials').

接下来,尝试失败时会呈现相同的登录页面。在您的登录模板中,您将拥有可变的消息,这基本上是您从视图发送的消息列表。您可以迭代它并在同一页面上显示它。