Django 表单即使应该返回验证错误也不返回?
Django form not returning validation error even when it is supposed to?
在控制台中我可以看到它打印了“Less”字符串,这意味着控件进入了“if len(f_N) < 2”,但是验证错误不是打印。请帮我看看代码有什么问题。
####我的 forms.py 文件:####
from django import forms
from django.core.exceptions import ValidationError
class UserRegistrationForm(forms.Form):
GENDER=[('male','MALE'),('female','FEMALE')]
firstName= forms.CharField()
lastName= forms.CharField()
email= forms.CharField(widget=forms.EmailInput,required=False,initial='Youremail@xmail.com')
address=forms.CharField(widget=forms.Textarea)
gender=forms.CharField(widget=forms.Select(choices=GENDER))
password=forms.CharField(widget=forms.PasswordInput)
ssn=forms.IntegerField()
def clean_firstName(self):
f_N=self.cleaned_data['firstName']
print(f_N)
if len(f_N)>15:
raise forms.ValidationError('Max length allowed is 15 characters')
if len(f_N) < 2:
print(len(f_N))
print("less")
raise forms.ValidationError('Min length showuld be 2 characters')
else:
print("end")
return f_N
#######我的 html 文件######
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Registration</title>
</head>
<body>
<h1> User Registration</h1>
<table>
<form method="post">
{% csrf_token %}
{{form.as_table}}
</table>
<button type="submit" name="button">Submit</button>
</form>
</body>
</html>
##########我的 views.py 文件##########
from django.shortcuts import render
from .forms import UserRegistrationForm
from .models import User
# Create your views here.
def UserRegistrationView(request):
form=UserRegistrationForm()
if request.method=='POST':
form_1=UserRegistrationForm(request.POST)
if form_1.is_valid() :
#print(form_1.cleaned_data)
form_1=form_1.cleaned_data
print(request.POST)
print(form_1)
user_1=User()
user_1.firstName=form_1['firstName']
user_1.lastName = form_1['lastName']
user_1.email = form_1['email']
user_1.save()
return render(request,'formsDemo/userRegistration.html',{'form':form})
参考这个话题https://docs.djangoproject.com/en/3.1/ref/forms/validation/#cleaning-a-specific-field-attribute
在您的 forms.py
中,您使用 from django.core.exceptions import ValidationError
以正确的方式导入了 ValidationError
,但随后您在函数 clean_firstName()
中以错误的方式提升了它,它应该是
raise ValidationError('..')
而不是
raise forms.ValidationError('..')
更新
在你的 views.py
中,因为你有 form_1=UserRegistrationForm(request.POST)
那么你应该将 form_1
传递给 render
语句中的上下文而不是 form
。任何你可以以正确的方式做事的方式(你不再需要第二个 form_1
):
def UserRegistrationView(request):
form=UserRegistrationForm()
if request.method=='POST':
form=UserRegistrationForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.save()
# Note:
# 1. if it happens 'form.is_valide()' returns false, then you'll
# get the errors in 'form.errors' bag.
# 2. you don't need to import User Model since you are using 'formMdel'
# maybe you need to redirect to home page if you successfully saved
# the new user .. display a flash message ..
return render(request,'formsDemo/userRegistration.html',{'form':form})
尝试像这样添加表单错误:
def clean_firstName(self):
f_N=self.cleaned_data['firstName']
print(f_N)
if len(f_N)>15:
self.add_error('firstName', 'Max length allowed is 15 characters')
if len(f_N) < 2:
print(len(f_N))
print("less")
self.add_error('firstName', 'Min length showuld be 2 characters')
else:
print("end")
return f_N
并确保始终返回已清理的 firstName
,因为使用您当前的代码,某些路径不会返回它。因此,为了解决这个问题,只需在所有 if
之外添加一个 return f_N
。
在控制台中我可以看到它打印了“Less”字符串,这意味着控件进入了“if len(f_N) < 2”,但是验证错误不是打印。请帮我看看代码有什么问题。
####我的 forms.py 文件:####
from django import forms
from django.core.exceptions import ValidationError
class UserRegistrationForm(forms.Form):
GENDER=[('male','MALE'),('female','FEMALE')]
firstName= forms.CharField()
lastName= forms.CharField()
email= forms.CharField(widget=forms.EmailInput,required=False,initial='Youremail@xmail.com')
address=forms.CharField(widget=forms.Textarea)
gender=forms.CharField(widget=forms.Select(choices=GENDER))
password=forms.CharField(widget=forms.PasswordInput)
ssn=forms.IntegerField()
def clean_firstName(self):
f_N=self.cleaned_data['firstName']
print(f_N)
if len(f_N)>15:
raise forms.ValidationError('Max length allowed is 15 characters')
if len(f_N) < 2:
print(len(f_N))
print("less")
raise forms.ValidationError('Min length showuld be 2 characters')
else:
print("end")
return f_N
#######我的 html 文件######
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Registration</title>
</head>
<body>
<h1> User Registration</h1>
<table>
<form method="post">
{% csrf_token %}
{{form.as_table}}
</table>
<button type="submit" name="button">Submit</button>
</form>
</body>
</html>
##########我的 views.py 文件##########
from django.shortcuts import render
from .forms import UserRegistrationForm
from .models import User
# Create your views here.
def UserRegistrationView(request):
form=UserRegistrationForm()
if request.method=='POST':
form_1=UserRegistrationForm(request.POST)
if form_1.is_valid() :
#print(form_1.cleaned_data)
form_1=form_1.cleaned_data
print(request.POST)
print(form_1)
user_1=User()
user_1.firstName=form_1['firstName']
user_1.lastName = form_1['lastName']
user_1.email = form_1['email']
user_1.save()
return render(request,'formsDemo/userRegistration.html',{'form':form})
参考这个话题https://docs.djangoproject.com/en/3.1/ref/forms/validation/#cleaning-a-specific-field-attribute
在您的 forms.py
中,您使用 from django.core.exceptions import ValidationError
以正确的方式导入了 ValidationError
,但随后您在函数 clean_firstName()
中以错误的方式提升了它,它应该是
raise ValidationError('..')
而不是
raise forms.ValidationError('..')
更新
在你的 views.py
中,因为你有 form_1=UserRegistrationForm(request.POST)
那么你应该将 form_1
传递给 render
语句中的上下文而不是 form
。任何你可以以正确的方式做事的方式(你不再需要第二个 form_1
):
def UserRegistrationView(request):
form=UserRegistrationForm()
if request.method=='POST':
form=UserRegistrationForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.save()
# Note:
# 1. if it happens 'form.is_valide()' returns false, then you'll
# get the errors in 'form.errors' bag.
# 2. you don't need to import User Model since you are using 'formMdel'
# maybe you need to redirect to home page if you successfully saved
# the new user .. display a flash message ..
return render(request,'formsDemo/userRegistration.html',{'form':form})
尝试像这样添加表单错误:
def clean_firstName(self):
f_N=self.cleaned_data['firstName']
print(f_N)
if len(f_N)>15:
self.add_error('firstName', 'Max length allowed is 15 characters')
if len(f_N) < 2:
print(len(f_N))
print("less")
self.add_error('firstName', 'Min length showuld be 2 characters')
else:
print("end")
return f_N
并确保始终返回已清理的 firstName
,因为使用您当前的代码,某些路径不会返回它。因此,为了解决这个问题,只需在所有 if
之外添加一个 return f_N
。