我想在我的html表单中显示一个类似“此电子邮件已在使用”的验证消息。你知道吗
但我想我遗漏了什么。我的邮箱里总是有一个完整的错误。如果我在模型中使用unique=True,Django不应该验证这个并给出ValidationError吗?还是我得亲自去抓那个完整的人?你知道吗
或者向我展示一个验证表单/模型中唯一用户的最佳实践。你知道吗
在型号.py你知道吗
class Customer(models.Model):
FirstName = models.CharField(max_length=50)
LastName = models.CharField(max_length=50)
Email = models.CharField(max_length=50, unique=True, error_messages={'unique':"This email is already in use"})
在视图.py你知道吗
def customerform(request):
if request.method == 'POST':
form = CustomerForm(request.POST)
if form.is_valid():
post = Customer()
post.FirstName = form.cleaned_data['FirstName']
post.LastName = form.cleaned_data['LastName']
post.Email = form.cleaned_data['Email']
post.save()
return render(request, 'results.html', {
'FirstName': form.cleaned_data['FirstName'],
'Email': form.cleaned_data['Email'],})
else:
form = CustomerForm()
return render(request, 'form.html', {'form':form})
在表单.py你知道吗
class CustomerForm(forms.Form):
FirstName = forms.CharField (label='First name:', max_length=50)
LastName = forms.CharField (label='Last name:', max_length=50)
Email = forms.EmailField(label='Email:', max_length=50)
在表单.html你知道吗
<form action="/customer/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
如果希望表单验证自动使用模型属性,则必须使用^{} :
如果要使用常规的
Form
,则需要手动执行验证。你知道吗相关问题 更多 >
编程相关推荐