一、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. 搞懂head 和 tail 命令

    情景 会点linux命令的人都知道head -n k和tail -n k(k≥0)的作用,但却不知道还支持head -n -k和tail -n +k的用法, 更不知道有着怎样的作用了. 图解 下面,用 ...

  2. 我的Android进阶之旅------>解决Jackson等第三方转换Json的开发包在开启混淆后转换的实体类数据都是null的bug

    1.错误描述 今天测试人员提了一个bug,说使用我们的app出现了闪退的bug,后来通过debug断点调试,发现我们的app转换服务器发送过来的json数据后,都是为null.而之前已经提测快一个月的 ...

  3. SQL SERVER常见等待——解决会话等待产生的系统问题

    SQL SERVER——解决会话等待产生的系统问题 转自: https://blog.csdn.net/z_cloud_for_SQL/article/details/55051215 版权声明:SQ ...

  4. Docker 网络之端口绑定

    外部访问容器 容器中可以运行一些网络应用,要让外部也可以访问这些应用,可以通过 -P 或 -p 参数来指定端口映射. -P 标记时 Docker 会随机映射一个 49000~49900 的端口到内部容 ...

  5. python16_day06【类、RE模块、subprocess模块、xml模块、shelve模块】

    一.shelve模块 import shelve # 基于pickle模块, d = shelve.open('shelve_test') class Test(object): def __init ...

  6. Python集合方法整理(Day9)

    #作用:去重,关系运算, #定义: 知识点回顾 可变类型是不可hash类型 不可变类型是可hash类型 #定义集合: 集合:可以包含多个元素,用逗号分割, 集合的元素遵循三个原则: 1:每个元素必须是 ...

  7. 用pytesseract识别验证码报错

    运行py文件出现下面报错 pytesseract.pytesseract.TesseractError: (1, 'Error opening data file \\Program Files\\T ...

  8. ThinkPHP框架基础知识二

    一.空操作和空控制器处理 空操作:没有指定的操作方法:空控制器:没有指定控制器,例如: http://网址/index.php/Home/Main/login  正常 http://网址/index. ...

  9. PAT 天梯赛 L1-011. A-B 【水】

    题目链接 https://www.patest.cn/contests/gplt/L1-011 AC代码 #include <iostream> #include <cstdio&g ...

  10. 002. MySQL复制操作

    #### 1.Setting the Replication Master Configuration On a replication master, you must enable binary  ...