定义forms表单:
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField(widget=forms.Textarea)
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
定义views视图:
from django.core.mail import send_mail
if form.is_valid():
subject = form.cleaned_data[‘subject‘]
message = form.cleaned_data[‘message‘]
sender = form.cleaned_data[‘sender‘]
cc_myself = form.cleaned_data["cc_myself"]
recipients = [‘info@example.com‘]
if cc_myself:
recipients.append(sender)
send_mail(subject,message,sender,recipients)
return HttpResponseRedirect(‘/thanks/‘)
创建表单模板文件:
<p><label for=‘id_subject‘>Subject:</label>
<input id="id_subject" type="text" name="subject" maxlength="100" /></p>
<p><label for=‘id_message‘>Message:</label>
<input id="id_message" type="text" name="message" /></p>
<p><label for=‘id_sender‘>Sender:</label>
<input id="id_sender" type="email" name="sender" " /></p>
<p><label for=‘id_cc_myself‘>Cc_myself:</label>
<input id="id_cc_myself" type="checkbox" name="id_cc_myself" /></p>
当然,在模板里面也是可以手工渲染字段
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.subject.errors }}
<label for="{{ form.subject.id_for_label }}">Email subject:</label>
{{ form.subject }}
</div>
<div class="fieldWrapper">
{{ form.message.errors }}
<label for="{{ form.message.id_for_label }}">Your message:</label>
{{ form.message }}
</div>
<div class="fieldWrapper">
{{ form.sender.errors }}
<label for="{{ form.sender.id_for_label }}">Your email address:</label>
{{ form.sender }}
</div>
<div class="fieldWrapper">
{{ form.cc_myself.errors }}
<label for="{{ form.cc_myself.id_for_label }}">CC yourself?:</label>
{{ form.cc_myself }}
</div>
本文出自 “13010688” 博客,请务必保留此出处http://13020688.blog.51cto.com/13010688/1941322
原文地址:http://13020688.blog.51cto.com/13010688/1941322