我阅读了这篇文章并发现代码中有错误 - 我可以通过表单发送“null”并且没有错误消息,它只是转到“感谢”页面。我可以在电子邮件字段中写“无”,结果将是相同的。如何解决?
楷模:
class Contact(forms.Form):
title = forms.CharField(max_length=100)
message = forms.CharField(max_length=255)
sender = forms.EmailField()
意见:
def contact(request):
if request.method == 'POST':
form = Contact(request.POST)
if form.is_valid():
title = form.cleaned_data['title']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
return HttpResponseRedirect('/thanks/')
else:
form = Contact()
return render(request, 'contact.html', {'form': form,})
模板:
<form action="/contact/" method="post">
{% csrf_token %}
{{ form.non_field_errors }}
{{ form.title.errors }}
<label for="id_subject">Subject</label>
{{ form.title }}
{{ form.message.errors }}
<label for="id_message">Text</label>
{{ form.message }}
{{ form.sender.errors }}
<label for="id_sender">Email</label>
{{ form.sender }}
<p><input type="submit" value="Send" /></p>
</form>