一、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. paper reading:gaze tracking

    https://www.cv-foundation.org/openaccess/content_cvpr_2016/papers/Krafka_Eye_Tracking_for_CVPR_2016_ ...

  2. ubuntu su failure when password was right

    https://blog.csdn.net/u013066244/article/details/52694540

  3. form表单学习

    1.http://www.cnblogs.com/fish-li/archive/2011/07/17/2108884.html 2.http://www.cnblogs.com/polk6/arch ...

  4. 我的Android进阶之旅------>关于使用Android Studio替换App的launcher图标之后仍然显示默认的ic_launcher图标的解决方法

    前言 最近做了一个App,之前开发该App的时候一直以来都是默认的launcher图标启动的, 今天美工换了一个App的launcher 图标,因此在Android Studio中将默认的lanche ...

  5. Mysql实现企业级日志管理、备份与恢复

    数据备份形式 文件备份: 通过Linux的备份命令把文件统一打个包存起来,可存在本地和远程服务器,等到要恢复时,再用这些文件恢复到指定位置. 数据库数据备份: 在一些对数据可靠性要求很高的行业如银行. ...

  6. Java Concurrent happens-before

    happens-before relation on memory operations such as reads and writes of shared variables. The resul ...

  7. HDU1838:Chessboard(线性dp)

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=1838 这题也挺不错的.首先题目说了,棋盘的右下角一定是'1',另外棋盘里面至少包含一个1,所以最小值是1, ...

  8. Python(变量、数据类型)

    常量:python中没有常量,只能通过名字特征来提示例如:全部大写,如 : OLDBOY_AGE=57 一.变量 变量声明变量#!/usr/bin/env python age=18gender1=' ...

  9. Typecho部署安装

    此文章已经在这里上. 如果您看到这篇文章,表示您的 blog 已经在digitalocean.com安装成功.下面说下安装的步骤,此文章都是在digitalocean.com的centos上成功安装: ...

  10. POJ - 2912 Rochambeau (带权并查集+枚举)

    题意:有N个人被分为了三组,其中有一个人是开了挂的.同组的人的关系是‘=’,不同组的人关系是‘<’或'>',但是开了挂的人可以给出自己和他人任意的关系.现在要根据M条关系找出这个开了挂的人 ...