我从不久前开始研究 Django 表单。我一直让表单由他们自己生成,只需编写:
{{ test_form.as_p }}
成功了。
然后我决定解决这个问题来定制这个模板,但由于某种原因,这条线:
{{ form.subject }}
不显示表格。我误解了文档吗?我还检查了生成的 HTML,它有点简单地跳过了 {{ form.suject }}
这是代码:
模板:
<form action="/contact/" method="post">
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.subject.errors }}
<label for="id_subject">Email subject:</label>
{{ form.subject }}
</div>
<div class="fieldWrapper">
{{ form.message.errors }}
<label for="id_message">Your message:</label>
{{ form.message }}
</div>
<div class="fieldWrapper">
{{ form.sender.errors }}
<label for="id_sender">Your email address:</label>
{{ form.sender }}
</div>
<p><input type="submit" value="Send message" /></p>
和相关的视图:
def contact(request):
if request.method == 'POST':
form = contact_form(data=request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
recipents = ['grit.erlum@gmail.com']
send_mail(subject, message, sender, recipents)
print 'mail sent'
return render_to_response('contact.html', {'contact_form' : contact_form}, context_instance=RequestContext(request))
当然还有表单类:
class contact_form(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField(max_length=1000, widget=forms.Textarea)
sender = forms.EmailField()