Django 表单在模板中未显示验证错误
python 548
原文标题 :Django form not showing validation error with in Templates
我正在尝试建立注册页面。我正在为我的注册表单字段编写自定义验证。但问题是表单没有引发验证错误。当我写 form.is_valid() 时,它显示已验证。我是 django 新手,正在学习新概念。我想弄清楚这里出了什么问题。
Forms.py file code :
from django import forms
from django.core import validators
def emptyField(value):
if value == '':
raise forms.ValidationError("Please fill all the fields .")
def length(value):
if len(value) > 20:
raise forms.ValidationError("Username can contain atmost 20 characters .")
class UserForm(forms.Form):
username = forms.CharField(required=False,validators=[emptyField,length])
email = forms.EmailField(required=False,validators=[emptyField])
password = forms.CharField(required=False,validators=[emptyField])
rePassword = forms.CharField(required=False,validators=[emptyField])
views.py file code :
from django.shortcuts import render,redirect
from .forms import UserForm
# Create your views here.
def home(request):
return render(request,"Users/home.html")
def registrationPage(request):
if request.method == "POST":
form = UserForm(request.POST)
if form.is_valid():
print("validated")
else:
form=UserForm()
context = {
"form": UserForm
}
return render(request,"Users/register.html",context)
register.html file code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title> REGISTRATION PAGE </title>
</head>
<body>
<h1> REGISTRATION PAGE </h1>
<form method="POST">
{% csrf_token %}
{{ form.username }}
{{ form.email }}
{{ form.password }}
{{ form.rePassword }}
<input type="submit" value="ADD">
</form>
</body>
</html>