一、django表单系统中,所有的表单类都作为django.forms.Form的之类创建,包括ModelForm

关于django的表单系统,主要分两种:

1.基于django.forms.Form:所有表单类的父类

2.基于django.forms.ModelForm:可以和模型类绑定的Form

案例:实现添加出版社信息的功能

二、不使用Django.Form的情况

add_publisher.html

<form action="" method="post">
{% csrf_token %}
名称:<input type="text" name="name"><br>
地址:<input type="text" name="address"><br>
城市:<input type="text" name="city"><br>
省份:<input type="text" name="state_province"><br>
国家:<input type="text" name="country"><br>
网址:<input type="text" name="website"><br>
名称:<input type="submit" value="提交"><br>
</form>

views.py

from django.http import HttpResponse
from django.shortcuts import render
from hello.models import Publisher def add_publisher(request):
if request.method == 'POST':
name = request.POST.get("name")
address = request.POST.get("address")
city = request.POST.get("city")
state_province = request.POST.get("state_province")
country = request.POST.get("country")
website = request.POST.get("website")
Publisher.objects.create(
name=name,
address=address,
city=city,
state_province=state_province,
country=country,
website=website,
)
return HttpResponse("Add Publisher Succ!")
else:
return render(request, 'add_publisher.html', locals())

三、使用Form的情况

add_publisher.html

<form action="{% url 'add_publisher' %}" method="post">
{% csrf_token %}
{{ publisher_form.as_p }}
{# {{ publisher_form.as_table }}#}
{# {{ publisher_form.as_ul }}#}
<input type="submit" value="提交">
</form>

forms.py

from django import forms

class PublisherForm(forms.Form):
name = forms.CharField(label="名称")
address = forms.CharField(label="地址")
city = forms.CharField(label="城市")
state_province = forms.CharField(label="省份")
country = forms.CharField(label="国家")
website = forms.URLField(label="网址")

views.py

from django.http import HttpResponse
from django.shortcuts import render
from hello.models import Publisher
from hello.forms import PublisherForm def add_publisher(request):
if request.method == 'POST':
publisher_form = PublisherForm(request.POST)
if publisher_form.is_valid():
Publisher.objects.create(
name=publisher_form.cleaned_data.get("name"),
address=publisher_form.cleaned_data.get("address"),
city=publisher_form.cleaned_data.get("city"),
state_province=publisher_form.cleaned_data.get("state_province"),
country=publisher_form.cleaned_data.get("country"),
website=publisher_form.cleaned_data.get("website"), )
return HttpResponse("Add Publisher Succ!")
else:
publisher_form = PublisherForm()
return render(request, 'add_publisher.html', locals())

四、使用ModelForm的情况

add_publisher.html

<form action="{% url 'add_publisher' %}" method="post">
{% csrf_token %}
{{ publisher_form.as_p }}
<input type="submit" value="提交">
</form>

forms.py

from django import forms
from hello.models import Publisher class PublisherForm(forms.ModelForm):
class Meta:
model = Publisher
exclude = ('id',)

views.py

from django.http import HttpResponse
from django.shortcuts import render
from hello.forms import PublisherForm def add_publisher(request):
if request.method == 'POST':
publisher_form = PublisherForm(request.POST)
if publisher_form.is_valid():
publisher_form.save()
return HttpResponse("Add Publisher Succ!")
else:
publisher_form = PublisherForm()
return render(request, 'add_publisher.html', locals())

总结:

使用Django中的Form可以大大简化代码,常用的表单功能特性都整合到了Form中,而ModelForm可以和Model进行绑定,更进一步简化操作。

更多详见:https://docs.djangoproject.com/en/1.10/ref/forms/api/

https://docs.djangoproject.com/en/1.10/ref/forms/fields/


***微信扫一扫,关注“python测试开发圈”,了解更多测试教程!***

Django进阶Form篇的更多相关文章

  1. Django进阶Model篇—数据库操作(ORM)

    一.数据库配置 django 默认支持sqlite.mysql.oracle.postgresql数据库,像db2和sqlserver之类的数据库需要第三方的支持,具体详见https://docs.d ...

  2. Django进阶Admin篇 - admin基本配置

    django admin 是django自带的一个后台app,提供了后台的管理功能. 基础知识点: 一.认识ModelAdmin 管理界面的定制类,如需扩展特定的model界面,需要从该类继承 二.注 ...

  3. Django进阶Model篇008 - 使用原生sql

    注意:使用原生sql的方式主要目的是解决一些很复杂的sql不能用ORM的方式写出的问题. 一.extra:结果集修改器-一种提供额外查询参数的机制 二.执行原始sql并返回模型实例 三.直接执行自定义 ...

  4. Django进阶Model篇007 - 聚集查询和分组查询

    接着前面的例子,举例聚集查询和分组查询例子如下: 1.查询人民邮电出版社出了多少本书 >>> Book.objects.filter(publisher__name='人民邮电出版社 ...

  5. Django进阶Model篇005 - QuerySet常用的API

    django.db.models.query.QuerySet QuerySet特点: 1.可迭代 2.可切片 查询相关API 1.get(**kwargs):返回与所给的筛选条件相匹配的对象,返回结 ...

  6. Django进阶Model篇004 - ORM常用操作

    一.增加 create和save方法 实例: 1.增加一条作者记录 >>> from hello.models import * >>> Author.object ...

  7. Django进阶Model篇002 - 模型类的定义

    一.创建数据模型. 实例: 作者模型:一个作者有姓名. 作者详情模型:把作者的详情放到详情表,包含性别.email 地址和出生日期,作者详情模型与作者模型之间是一对一的关系(OneToOneField ...

  8. Django进阶Model篇001 - mysql 数据库的配置

    django 默认支持sqlite.mysql.oracle.postgresql数据库,像db2和sqlserver之类的数据库需要第三方的支持,具体详见: https://docs.djangop ...

  9. Django进阶Template篇002 - 模板包含和继承

    包含 {% include %} 允许在模板中包含其他模板的内容. {% include "foo/bar.html" %} {% include template_name %} ...

随机推荐

  1. 指定文件夹 指定文件后缀名 删除整个文件夹 git 冲突解决 create a new repository on the command line push an existing repository from the command line

    http://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000/001375840038939c2 ...

  2. tomcat 6 利用ExpiresFilter控制静态文件缓存

    在tomcat7下面 利用ExpiresFilter来控制静态文件缓存很方便,按照tomcat官网手动配置即可: 但是tomcat6 里面并没有 org.apache.catalina.filters ...

  3. cas添加验证码

    cas添加验证码,折腾了好久,终于整理好了,很大部分都是借鉴http://binghejinjun.iteye.com/blog/1255293这个的.但是他的有一个很不好的地方就是不能提升验证码错误 ...

  4. Hbase 学习笔记4----原理

    MapReduce 中如何处理HBase中的数据?如何读取HBase数据给Map?如何将结果存储到HBase中? Mapper类:包括一个内部类(Context)和四个方法(setup,map,cle ...

  5. HTTP状态码集

    1xx消息 这一类型的状态码,代表请求已被接受,需要继续处理.这类响应是临时响应,只包含状态行和某些可选的响应头信息,并以空行结束.由于HTTP/1.0协议中没有定义任何1xx状态码,所以除非在某些试 ...

  6. Nhibernate工具Profiler配置

    1.使用之前需要确认Framework的Version,如果是4.0那么使用如下程序集需要在 创建ISessionFactory的项目中引用NHProfiler安装目录下的 HibernatingRh ...

  7. redmine安装及SVN(https)配置

    一键安装redmine https://blog.csdn.net/qq_26898315/article/details/50233483 配置SVN(引用: https://blog.csdn.n ...

  8. form:checkboxes radiobutton select用法

    <form:checkboxes path="subjects" items="${requestScope.subjects}" element=&qu ...

  9. POJ 3463 Sightseeing (次短路)

    题意:求两点之间最短路的数目加上比最短路长度大1的路径数目 分析:可以转化为求最短路和次短路的问题,如果次短路比最短路大1,那么结果就是最短路数目加上次短路数目,否则就不加. 求解次短路的过程也是基于 ...

  10. git-bash使用ctrl C无法终止nodemon的执行

    原因: git的bug 解决:git版本降级为2.10.0好了