Django表单,字段空错误没有被提出

时间:2017-03-10 17:28:50

标签: django forms

我正在尝试使用django + xadmin构建博客,并使用django表单来显示&验证用户名和密码。

forms.py

from django import forms

class LoginForm(forms.Form):
    username = forms.CharField(required=True,)
    password = forms.CharField(required=True, min_length=5)

views.py

from django.views.generic.base import View
# Create your views here.

from .models import UserProfile
from .forms import LoginForm


class CustomBackend(ModelBackend):
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username)|Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


class LoginView(View):
    def get(self, request):
        return render(request, "login.html", {})

    def post(self, request):
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            user_name = request.POST.get("username","")
            pass_word = request.POST.get("password","")
            user = authenticate(username=user_name, password=pass_word)
            if user is not None:
                login(request,user)
                return render(request,"index.html")
            else:
                return render(request, "login.html", {"msg": "username or password is uncorrect", })

        else:
            return render(request,"login.html",{"login_form":login_form.errors})

当我在if login_form.is_valid():设置断点并使用空用户名和密码对其进行测试时,会引发所需的错误。当我看到login_form的细节时,_errors就是none。它不应该打勾。 我应该更改我的代码以修复此错误。

我已将login.html粘贴到此处,我该如何更改呢。

<form action="/login/" method="post" autocomplete="off">
{% csrf_token %}
<div class="form-group marb20 {% if login_form.errors.username %}errorput{% endif %}">
    <label>UserName</label>
    <input name="username" id="account_l" type="text"  />
</div>
<div class="form-group marb8 {% if login_form.errors.password %}errorput{% endif %}">
    <label>PassWord</label>
    <input name="password" id="password_l" type="password"  />
</div>

<div class="error btns login-form-tips" id="jsLoginTips">{% for key,error in login_form.erroes.items %}{{error}}{% endfor %}{{ msg }}</div>
 <div class="auto-box marb38">

    <a class="fr" href="forgetpwd.html">forget the password?</a>
 </div>
 <input class="btn btn-green" id="jsLoginBtn" type="submit" value="sign_in > " />
{% csrf_token %}
</form>

2 个答案:

答案 0 :(得分:0)

我没有看到您甚至已将表单从您的视图传递到模板。当你调用render时,它应该是这样的:

    render(request,"login.html", {'login_form': login_form})

现在,如果您在模板中正确使用login_form,请执行以下操作:

    <div class='form-group'>
        {{login_form.username}}
        {{login_form.password}}
    </div>

这将为您处理错误并显示它们。如果你想要更精细的控制,你可以这样做:

{% for field in login_form %}
    <div class="fieldWrapper">
        {{ field.errors }}
        {{ field.label_tag }} {{ field }}
        {% if field.help_text %}
        <p class="help">{{ field.help_text|safe }}</p>
        {% endif %}
    </div>
{% endfor %}

现在您可以修改每个元素。有关表单呈现和此示例的更多信息,请阅读此内容:https://docs.djangoproject.com/en/1.10/topics/forms/#form-rendering-options

修改

    <form action="/login/" method="post" autocomplete="off">
{% csrf_token %}
<div class="form-group marb20 {% if login_form.errors.username %}errorput{% endif %}">
    {{login_form.username}}        
</div>
<div class="form-group marb8 {% if login_form.errors.password %}errorput{% endif %}">
   {{login_form.password}}
</div>

<div class="error btns login-form-tips" id="jsLoginTips">{% for key,error in login_form.erroes.items %}{{error}}{% endfor %}{{ msg }}</div>
 <div class="auto-box marb38">

    <a class="fr" href="forgetpwd.html">forget the password?</a>
 </div>
 <input class="btn btn-green" id="jsLoginBtn" type="submit" value="sign_in > " />
{% csrf_token %}
</form>

答案 1 :(得分:0)

如果表单无效,您必须传递 login_form ,如下所示。因为您正在访问模板中的 login_form.errors.username

def post(self, request):
    login_form = LoginForm(request.POST)
    if login_form.is_valid():
        ....
    else:
        return render(request,"login.html",{"login_form":login_form})