我是 Django 新手。在这里,每当我提交表单时,即使我在填写表单时犯了错误,也不会出现验证错误,而且验证错误在前端也不可见。尽快寻求帮助
views.py
from django.shortcuts import render
from testform import form
from django.http import HttpResponse
# Create your views here.
def studentform(request):
studentrecord=form.Student()
data={'data':studentrecord}
if request.method=='POST':
studentrecord=form.Student(request.POST)
if studentrecord.is_valid():
print('validating')
print('sname',studentrecord.cleaned_data['Name'])
print('sloc',studentrecord.cleaned_data['location'])
print('smail',studentrecord.cleaned_data['mail'])
else:
print('form is not valid')
return HttpResponse('thanks for form filling')
return render (request,'testform/try.html',context=data)
表单.py
from django import forms
class Student(forms.Form):
Name=forms.CharField()
location=forms.CharField()
mail=forms.EmailField()
course=forms.CharField()
def clean(self):
total_clean=super().clean()
inputname=total_clean['Name']
if len(inputname)<5:
raise forms.ValidationError('Type the name in below 5 letters')
input_location=total_clean['location']
if input_location =='Antartica':
raise forms.ValidationError('Antartica is not valid')
input_course=total_clean['course']
if input_course not in ['python','java']:
raise forms.ValidationError('select either python or java')
我认为您错过了在 html 文件中添加表单错误标签。 添加了类似这样的内容。
<body>
<!-- your html elements -->
{{form.errors}}
</body>
视图逻辑始终会显示表单已正确填写,即使没有正确填写。
def studentform(request):
if request.method == 'POST':
studentrecord = form.Student(request.POST)
if studentrecord.is_valid():
print('validating')
print('sname', studentrecord.cleaned_data['Name'])
print('sloc', studentrecord.cleaned_data['location'])
print('smail', studentrecord.cleaned_data['mail'])
return HttpResponse('thanks for form filling')
else:
studentrecord = form.Student()
data = {'data': studentrecord}
return render(request, 'testform/try.html', context=data)
在表单中,还应该返回清理后的数据:
从 django 导入表单
from django import forms
class Student(forms.Form):
# …
def clean(self):
total_clean = super().clean()
inputname = total_clean['Name']
if len(inputname) < 5:
raise forms.ValidationError('Type the name in below 5 letters')
input_location = total_clean['location']
if input_location == 'Antartica':
raise forms.ValidationError('Antartica is not valid')
input_course = total_clean['course']
if input_course not in ['python', 'java']:
raise forms.ValidationError('select either python or java')
return total_clean