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

9:django 表单的更多相关文章

  1. python 全栈开发,Day111(客户管理之 编辑权限(二),Django表单集合Formset,ORM之limit_choices_to,构造家族结构)

    昨日内容回顾 1. 权限系统的流程? 2. 权限的表有几个? 3. 技术点 中间件 session orm - 去重 - 去空 inclusion_tag filter 有序字典 settings配置 ...

  2. python3之Django表单(一)

    1.HTML中的表单 在HTML种,表单是在<form>...</form>种的元素,它允许用户输入文本,选择选项,操作对象等,然后发送这些数据到服务器 表单元素允许用户在表单 ...

  3. django表单的api

    django表单的api,参考文档:https://yiyibooks.cn/xx/Django_1.11.6/ref/forms/api.html 绑定与未绑定形式: Form要么是绑定的,要么是未 ...

  4. Django表单API详解

    声明:以下的Form.表单等术语都指的的广义的Django表单. Form要么是绑定了数据的,要么是未绑定数据的. 如果是绑定的,那么它能够验证数据,并渲染表单及其数据,然后生成HTML表单.如果未绑 ...

  5. django 表单系统 之 forms.Form

    继承forms.Form实现django表单系统 参考: https://www.cnblogs.com/zongfa/p/7709639.html https://www.cnblogs.com/c ...

  6. 关于创建Django表单Forms继承BaseForm的问题

    在创建Django表单时,因为需要验证用户输入的验证码是否正确,因此需要在session里提取当前验证码的值和POST提交过来的值进行比对,如图: form.py from django import ...

  7. Django 表单处理流程

    Django 的表单处理:视图获取请求,执行所需的任何操作,包括从模型中读取数据,然后生成并返回HTML页面(从模板中),我们传递一个包含要显示的数据的上下文.使事情变得更复杂的是,服务器还需要能够处 ...

  8. 第四章:Django表单 - 2:Django表单API详解

    声明:以下的Form.表单等术语都指的的广义的Django表单. Form要么是绑定了数据的,要么是未绑定数据的. 如果是绑定的,那么它能够验证数据,并渲染表单及其数据,然后生成HTML表单.如果未绑 ...

  9. 第四章:Django表单 - 1:使用表单

    假设你想从表单接收用户名数据,一般情况下,你需要在HTML中手动编写一个如下的表单元素: <form action="/your-name/" method="po ...

随机推荐

  1. bzoj1024: [SCOI2009]生日快乐(DFS)

    dfs(x,y,n)表示长为x,宽为y,切n块 每次砍的一定是x/n的倍数或者y/n的倍数 #include<bits/stdc++.h> using namespace std; con ...

  2. 15ecjtu校赛1006 (dfs容斥)

    Problem Description 在平面上有一个n*n的网格,即有n条平行于x轴的直线和n条平行于y轴的直线,形 成了n*n个交点(a,b)(1<=a<=n,1<=b<= ...

  3. 【题解】最大公约数之和 V3 51nod 1237 杜教筛

    题目传送门 http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1237 数学题真是做的又爽又痛苦,爽在于只要推出来公式基本上就 ...

  4. ZooKeeper概述(三)

    ZooKeeper:分布式应用的分布协调服务 ZooKeeper是一个为分布式应用提供的分布的开源的协调服务.它暴露一组简单的原子操作,分布式系统可以在这之上为同步,配置管理,和组和命名实现更高级的服 ...

  5. 多条select语句的合并

    select (') , (') , (select max(ssq) from DW_MARK_FXJS.F_GS_YCXJJDCSY@new_zgxt ) from dual 这样就不用傻傻的执行 ...

  6. zoj 2006 Glass Beads

    Glass Beadshttp://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1006 Time Limit: 2 Seconds     ...

  7. [Luogu 3224] HNOI2012 永无乡

    [Luogu 3224] HNOI2012 永无乡 特别水一个平衡树题. 不认真的代价是调试时间指数增长. 我写的 SBT,因为 Treap 的 rand() 实在写够了. 用并查集维护这些点的关系, ...

  8. Canvas 基本绘图方法总结

    一.基本内容  1.简单来说,HTML5提供的新元素<canvas>  2.Canvas在HTML页面提供画布的功能,在画布中绘制各种图形  3.Canvas绘制的图形与HTML页面无关, ...

  9. POJ 2991 Crane (线段树)

    题目链接 Description ACM has bought a new crane (crane -- jeřáb) . The crane consists of n segments of v ...

  10. auto-keras 测试保存导入模型

    # coding:utf-8 import time import matplotlib.pyplot as plt from autokeras import ImageClassifier# 保存 ...