一、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. MySQL优化方案二

    摘自:http://www.thinkphp.cn/topic/3855.html 今天,数据库的操作越来越成为整个应用的性能瓶颈了,这点对于Web应用尤其明显.关于数据库的性能,这并不只是DBA才需 ...

  2. Pycharm如何修改背景图(BackgroundColor)

    Outline 之前见到别人Eclipse自定义设置了背景图,在想 Pycharm是不是也可以设置?都是IDE嘛~ 没事捣鼓 Pycharm Settings 时,看到“Background Imag ...

  3. 初识python(二)

    初识python(二) 1.变量 变量:把程序运行的中间结果临时的存在内存里,以便后续的代码调用. 1.1 声明变量: #!/usr/bin/env python # -*- coding: utf- ...

  4. Pantone色卡——安全装备的面板、丝印及铭牌颜色设计参考

    可以参考上传文件<Pantone色卡电子版下载>

  5. 使用Free命令查看Linux服务器内存使用状况(-/+ buffers/cache详解)

    free命令可选参数 -b,-k,-m,-g show output in bytes, KB, MB, or GB -h human readable output (automatic unit ...

  6. 深入ff and ffbase

    用ff 包读取一个csv 文件 >options(fftempdir = [二进制文件存放的位置]) >file_chunks <- read.csv.ffdf(file=”big_ ...

  7. CKEditor的下载、配置与使用

    CKEditor简介: CKEditor 是一款功能强大的开源在线文本编辑器.它所见即所得的特点,使你在编辑时所看到的内容和格式,能够与发布后看到的效果完全一致.CKEditor 完全是基于 Java ...

  8. C#驱动级模拟按键操作

    C#驱动级模拟按键操作 2013-09-26 03:17 ·AB叔 447 3 <- 点击左侧的数字“攒”一个吧 昨天遇到一个程序自动输入财付通密码的任务. 因为财付通密码控件是有安全保护的,所 ...

  9. ArcEngine开发中“错误类型"****"未定义构造函数”

    from:http://blog.csdn.net/mengdong_zy/article/details/8990593 问题 在ArcEngine开发的时候,在编译时,发现出现这样的错误,出错的地 ...

  10. MAC mysql install

    # linux 查看是否安装mysql   rpm -qa |grep mysql    yum 安装mysql      yum -y install mysql-server 1 download ...