码迷,mamicode.com
首页 > 其他好文 > 详细

django Form表单模块实例(一)

时间:2017-06-23 20:55:04      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:python   form   

定义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

django Form表单模块实例(一)

标签:python   form   

原文地址:http://13020688.blog.51cto.com/13010688/1941322

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!