我不久前就开始研究Django表单了。我一直只是通过写作来让他们自己生成表格:
{{ test_form.as_p }}
成功地运作了。
然后我决定尝试自定义此模板,但由于某种原因,该行:
{{ form.subject }}
未显示表单。我误解了documentation吗?我还检查了生成的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))
当然还有Form Class:
class contact_form(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField(max_length=1000, widget=forms.Textarea)
sender = forms.EmailField()
答案 0 :(得分:1)
在你的render_to_response中,只需更改:
{'contact_form':contact_form}
到
{'form':contact_form}
或您的模板,将{{form.xxx}}更改为{{contact_form.xxx}}
答案 1 :(得分:0)
您的视图未定义contact_form
变量,但您将其传递给render_to_response
。
您还需要创建表单的未绑定版本,并将其传递给render_to_response
,如:
def contact(request):
if request.method == 'POST':
form = contact_form(data=request.POST)
if form.is_valid():
...
else:
form = contact_form() # An unbound form
return render_to_response('contact.html', {'form' : form}, context_instance=RequestContext(request))