如何在 Django 表单中显示验证错误?

How to show the validation error in a Django form?

我是 Django 的新手。我正在尝试制作一个简单的表格来匹配密码。但是,当我输入不同的密码并按下“保存”按钮时,我得到了一个已清除的表单,而不是显示验证错误。

这里newuser.html:

{% block content %}
<form method="POST">
{% csrf_token %}
    <table>
        {{frmNewUser.as_table}}
        {% for error in frmNewUser.password.errors %} {% comment %} I tried frmNewUser.non_field_errors too {% endcomment %}
            <p>{{error}}</p>
        {% endfor %}
    </table>
    <input type="submit" name="Save" value="Save" colspan=2>
</form>
{% endblock content %}

这里forms.py:

class NewUserFrom(forms.Form):
    username = forms.CharField(max_length=50, widget=forms.TextInput)
    password = forms.CharField(widget=forms.PasswordInput)
    confirm_password = forms.CharField(label="Confirm password", widget=forms.PasswordInput)
    name = forms.CharField(max_length=50, widget=forms.TextInput)
    email = forms.EmailField(max_length=50, widget=forms.EmailInput)

    def clean(self):
        cleaned_data = super().clean()
        pwd = cleaned_data.get('password')
        cof_pwd = cleaned_data.get('confirm_password')
        if pwd and cof_pwd:
            if pwd != cof_pwd:
                raise forms.ValidationError('Password is not match.')
        return super().clean()

这里views.py:

from django.shortcuts import render
from django.http import HttpResponse, request
from django.db import connection
from django.contrib.auth.decorators import login_required
import pyodbc
from .forms import NewUserFrom

def newUser(request):    
     
     form = NewUserFrom(request.POST)
     if not form.is_valid():     
          return render(request,'login/newuser.html', {'frmNewUser':NewUserFrom})
     return render(request, "login/welcome.html")

试试这个 article,它在我遇到类似问题时很有帮助

在新用户函数中

def newUser(request):    
     
     form = NewUserFrom(request.POST)
     if not form.is_valid():     
          return render(request,'login/newuser.html', {'frmNewUser':NewUserFrom})
     return render(request, "login/welcome.html")

if 语句中的 return 值应从 {'frmNewUser':NewUserFrom}) 更改为 {'frmNewUser':form})