【发布时间】:2016-12-29 16:42:00
【问题描述】:
我在表单中呈现错误时遇到问题,当表单无效时,它只是重新加载页面并且错误不显示。 我想显示错误,例如显示电子邮件无效或电话号码包含无效字符的文本
这是我的代码:
views.py
def contact(request):
form_class = ContactForm
if request.method == 'POST':
form = form_class(data=request.POST)
if form.is_valid():
contact_name = request.POST.get(
'contact_name'
, '')
contact_email = request.POST.get(
'contact_email'
, '')
contact_phone = request.POST.get(
'contact_phone'
, '')
form_content = request.POST.get(
'content'
, '')
# Email the profile with the
# contact information
template = get_template('contact_form.txt')
context = Context({
'contact_name': contact_name,
'contact_email': contact_email,
'contact_phone': contact_phone,
'form_content': form_content,
})
content = template.render(context)
email = EmailMessage(
"Novo contato pelo site",
content,
"email@gmail.com",
['myemail@hotmail.com'],
headers={'Reply-To': contact_email}
)
email.send()
print(form.cleaned_data)
else:
print(form)
return render(request, 'info/contact_us.html', {
'form': form_class,
})
forms.py
class ContactForm(forms.Form):
contact_name = forms.CharField(max_length=150,
label="Nome",
required=True,)
contact_email = forms.EmailField(max_length=150,
label="Email",
required=True,)
contact_phone = forms.RegexField(max_length=12,
label="Fone",
required=False,
regex=r'[0-9]+',)
content = forms.CharField(max_length=10000,
required=True,
widget=forms.Textarea,)
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.form_id = 'id-form'
self.helper.form_class = 'blueForms'
self.helper.form_method = 'post'
self.helper.form_action = ''
self.helper.add_input(Submit('submit', 'Submit'))
self.fields['contact_name'].label = "Name:"
self.fields['contact_email'].label = "Email:"
self.fields['contact_phone'].label = "Phone:"
self.fields['content'].label = "Message:"
def clean(self):
cleaned_data = super(ContactForm, self).clean()
contact_name = cleaned_data.get("contact_name")
contact_email = cleaned_data.get("contact_email")
contact_phone = cleaned_data.get("contact_phone")
content = cleaned_data.get("content")
if 'asd' not in contact_email:
raise forms.ValidationError("Invalid Email")
contact_us.html
<div id="form" class="col-sm-6">
{% crispy form form.helper %}
</div>
【问题讨论】:
-
该视图的其余部分在哪里?目前,您会收到该代码的服务器错误。
-
糟糕,刚刚添加了我忘记的最后一部分。
标签: python django django-forms