码迷,mamicode.com
首页 > 其他好文 > 详细

django下Form表单的使用(一)

时间:2018-01-30 00:15:54      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:api   local   ddr   ken   .post   代码   操作   gpo   cti   

一、什么是Form?什么是Django Form?
django表单系统中,所有的表单类都作为django.forms.Form的子类创建,包括ModelForm
关于django的表单系统,主要分两种

基于django.forms.Form:所有表单类的父类
基于django.forms.ModelForm:可以和模型类绑定的Form

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

二、不使用Django Form的情况(原生的写html实现表单提交)

add_publisher.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加出版社信息</title>
</head>
<body>
<form action="{% url ‘add_publisher‘ %}" 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" name="添加"><br>
</body>
</html>


views中的控制语句:
def add_publisher(request):
if request.method == "POST":
#如果为post提交,去接收用户提交过来的数据
name = request.POST[‘name‘]
address = request.POST[‘address‘]
city = request.POST[‘city‘]
state_province = request.POST[‘state_province‘]
country = request.POST[‘country‘]
website = request.POST[‘website‘]
Publisher.objects.create(
name=name,
address=address,
city=city,
state_province=state_province,
website=website,
)
return HttpResponse("添加出版社信息成功")
else:
return render(request,‘add_publisher.html‘,locals())

 

 

三、使用Form的情况
四、使用ModelForm的情况

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

查看forms相关资料:
https://docs.djangoproject.com/en/1.9/ref/forms/api/
https://docs.djangoproject.com/en/1.9/ref/forms/fields/

django下Form表单的使用(一)

标签:api   local   ddr   ken   .post   代码   操作   gpo   cti   

原文地址:https://www.cnblogs.com/kindnull/p/8379804.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!