django Form表单模块实例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django 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 = [‘[email protected]‘]
   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表单模块实例的主要内容,如果未能解决你的问题,请参考以下文章

django Form模块实例

Django Form组件实例:登录界面[Form表单提交,Ajax提交]

Django框架form表单配合ajax注册

django下Form表单的使用

Django表单API详解

Django Form表单