我正在联系表格。当我让Django在我的模板中用{{ form.as_p }}
解压缩表单的字段时,它呈现得很好,但如果我不想手动渲染字段,那么我就有问题了。
我想要的是在字段未实现时添加错误消息。
这是我使用django文档https://docs.djangoproject.com/en/1.8/topics/forms/
所做的<form role="form" method="post">
{% csrf_token %}
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.contact_name.errors }}
<label for="{{ form.contact_name.id_for_label }}">Name:</label>
{{ form.contact_name }}
</div>
<div class="fieldWrapper">
{{ form.content.errors }}
<label for="{{ form.content.id_for_label }}">Message:</label>
{{ form.content }}
</div>
<div class="fieldWrapper">
{{ form.contact_email.errors }}
<label for="{{ form.contact_email.id_for_label }}">Email:</label>
{{ form.contact_email }}
</div>
<input type="submit" value="Submit" />
</form>
但如果某些字段未实现,我不会收到错误消息。
我只是在else form = form_class()
这是我现在使用的代码:
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', '')
form_content = request.POST.get('content', '')
template = get_template('agency/contact_template.txt')
context = Context({
'contact_name': contact_name,
'contact_email': contact_email,
'form_content': form_content,
})
content = template.render(context)
email = EmailMessage(
"New messages",
content,
"My web site " + '<good@day.com>',
['user@gmail.com'],
headers = {'Message respond to': contact_email}
)
email.send()
return render_to_response('papers/thank_you.html', {}, context_instance=RequestContext(request))
else:
form = form_class()
return render_to_response('papers/contact.html', {'form': form_class}, context_instance=RequestContext(request))
contact.html
<form role="form" id="contact-form" action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<p class="contact-submit">
<button id="contact-submit" class="submit" type="submit" value="Submit">Send</button>
</p>
</form>
forms.py
from django import forms
class ContactForm(forms.Form):
contact_name = forms.CharField(required=True)
contact_email = forms.EmailField(required=True,)
content = forms.CharField(
required=True,
widget=forms.Textarea)
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.fields['contact_name'].label = "Name:"
self.fields['contact_email'].label = "Email:"
self.fields['content'].label = "Message"
答案 0 :(得分:1)
您的缩进不正确。 else
块应与if request.method == POST
一致。
if request.method == 'POST':
form = form_class(data=request.POST)
if form.is_valid():
# process form and return response
else:
form = form_class()
这样,当表单无效时,将使用带有post数据的绑定表单,并且将向用户显示任何错误。由于你有required=True
,如果必填字段留空,Django会自动添加错误。
其次,在渲染模板时,需要传递表单,而不是表单类。
return render_to_response('papers/contact.html', {'form': form}, context_instance=RequestContext(request))
最后,在发送电子邮件后重定向到“谢谢”页面是个好主意,而不是渲染“谢谢”模板。如果用户刷新感谢页面,则会停止发送多封电子邮件。