以下是我创建表单的代码:
from django import forms
class Register(forms.Form):
username = forms.CharField(label='', max_length=64, required=True)
firstname = forms.CharField(label='', max_length=64, required=True)
surname = forms.CharField(label='sur name', max_length=64, required=True)
email = forms.EmailField()
我的view.py代码如下:
from .forms import Register
def register(request):
form = Register()
return render(request, 'app/register.html', {'form': form})
它在网页中显示表单,但不验证用户名,名字和姓氏;而它验证了电子邮件领域。
我尝试使用clean方法,我的新forms.py如下:
from django import forms
class Register(forms.Form):
username = forms.CharField(label='', max_length=64, required=True)
firstname = forms.CharField(label='', max_length=64, required=True)
surname = forms.CharField(label='sur name', max_length=64, required=True)
email = forms.EmailField()
def clean_surname(self):
data = self.cleaned_data['surname']
if not data:
raise forms.ValidationError("This field is required")
return data
可能是什么问题?难道我做错了什么。请帮帮我,我是Django的新手。
答案 0 :(得分:4)
要验证表单,您需要使用POST请求中的数据填充表单并检查它是否有效。您的观点应如下所示:
from .forms import Register
def register(request):
if request.method == 'POST' # process form data
# create form instance, populate it with data
form = Register(request.POST)
# check if the data is valid
if form.is_valid():
# process/save the data
# ...
# then redirect to a new URL:
return HttpResponseRedirect('/a/new/url/')
else:
# GET or other method, create a blank form
form = Register()
return render(request, 'app/register.html', {'form': form})
中的更多内容
答案 1 :(得分:1)
您没有将帖子数据传递到表单中。它应该是这样的:
from .forms import Register
def register(request):
form = Register(request.POST or None)
if request.method == 'POST' and form.is_valid():
# your action when form is valid
else:
return render(request, 'app/register.html', {'form': form})
在or None
之后 request.POST
将确保空的POST字典不会传递到您的表单中,因此在第一次加载页面时不会触发验证 - 当没有提交任何内容时。
此外,电子邮件字段的验证可能来自您的浏览器,而不是来自django。