django自带表单系统,这个表单系统不仅可以定义属性名,还可以自己定义验证,更有自己自带的错误提示系统

这节我们仅仅粗略的来看一下django表单系统的入门运用(具体的实在太多东西,主要是我觉得有很多东西不是很适合现在的我使用,等以后需要的时候再回来看看吧)

定义表单

from django import forms
#所有的表单类都应该是forms.Form的子类
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)

如果你想在现有的model建立表单,可以这样写

from django.forms import ModelForm
# Create the form class.
class ArticleForm(ModelForm):
class Meta:
model = Article

在视图函数中使用表单

from django.shortcuts import render
from django.http import HttpResponseRedirect def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
subject = form.cleaned_data['subject']#使用cleaned_data而不是request.POST,因为前者前者不仅已经通过验证并且都是所有的内容都已经转成了符合python标准的类型
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) from django.core.mail import send_mail
send_mail(subject, message, sender, recipients)
return HttpResponseRedirect('/thanks/') # Redirect after POST
return HttpResponseRedirect('/thanks/') # Redirect after POST else: form = ContactForm() # An unbound form return render(request, 'contact.html', { 'form': form, })

在模板中使用表单

<form action="/contact/" method="post">
{% csrf_token %}<!-- djnago 强制使用跨站点请求伪造保护(Cross Site Request Forgery protection)-->
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>

form.as_p的效果如下:

<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 type="text" name="message" id="id_message" /></p>
<p><label for="id_sender">Sender:</label>
<input type="text" name="sender" id="id_sender" /></p>
<p><label for="id_cc_myself">Cc myself:</label>
<input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>

如果你不想使用django默认的模板,可以自定义自己的模板,示例如下

<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>
<div class="fieldWrapper">
{{ form.cc_myself.errors }}
<label for="id_cc_myself">CC yourself?</label>
{{ form.cc_myself }}
</div>
<p><input type="submit" value="Send message" /></p>
</form>

你可以这样遍历表单域

<form action="/contact/" method="post">
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }}: {{ field }}
</div>
{% endfor %}
<p><input type="submit" value="Send message" /></p>
</form>

下面是每个{{filed}}都应该有的属性

{{ field.label }}
The label of the field, e.g. Email address.
{{ field.label_tag }}
The field’s label wrapped in the appropriate HTML <label> tag, e.g. <label for="id_email">Email address</label>
{{ field.value }}
The value of the field. e.g someone@example.com
{{ field.html_name }}
The name of the field that will be used in the input element’s name field. This takes the form prefix into account, if it has been set.
{{ field.help_text }}
Any help text that has been associated with the field.
{{ field.errors }}
Outputs a <ul class="errorlist"> containing any validation errors corresponding to this field. You can customize the presentation of the errors with a {% for error in field.errors %} loop. In this case, each object in the loop is a simple string containing the error message.
field.is_hidden
This attribute is True if the form field is a hidden field and False otherwise. It’s not particularly useful as a template variable, but could be useful in conditional tests such as: {% if field.is_hidden %}
{# Do something special #}
{% endif %}

p

最新文章

  1. 【Java每日一题】20161229
  2. CS193P - 2016年秋 第一讲 课程简介
  3. ubuntu-kylin16.04搭建lamp环境。
  4. Java/Android引用类型及其使用分析
  5. 【HTML点滴】WWW简介
  6. 备忘:SSRS技巧三则
  7. DIV的表单布局
  8. Error Dropping Database (Can&#39;t rmdir &#39;.test\&#39;, errno: 17)
  9. JS字符串操作大全
  10. [ACM] hdu 4405 Aeroplane chess (概率DP)
  11. 安装appuim
  12. HTML行内元素、块状元素、行内块状元素的区别
  13. Scala入门系列(九):函数式编程
  14. Java JTS &amp; 空间数据模型
  15. php的打印sql语句的方法
  16. 设置pip代理
  17. 1.Windows下使用VisualSVN Server搭建SVN服务器
  18. struts2拦截器demo
  19. phoenix elixir 框架简单试用
  20. MIS货物拆包销售的问题

热门文章

  1. BZOJ2115:[WC2011]Xor——题解
  2. 快速搭建http服务:共享文件--Java的我,不知Python你的好
  3. &quot;HK&quot;日常之冻结术
  4. bzoj3224: Tyvj 1728 普通平衡树(打个splay暖暖手)
  5. PHP中缓存技术
  6. 【单调队列】【P2627】 修剪草坪
  7. ACE_DEBUG介绍及日志输出
  8. HDU 4549 矩阵快速幂+快速幂+欧拉函数
  9. 编译skia静态库时,图片解码库无法注册的问题
  10. centos6.5 配置mongodb3