Django表单提交一共有三种方式:

1.不使用Django组件进行提交

2.使用django.forms.Form(所有表单类的父类)进行提交

3.使用django.forms.ModelForm(可以和模型绑定的Form)进行提交

这里的例子是,给Publisher这个表里添加数据,表结构如下:

class Publisher(models.Model):
name = models.CharField("名称",max_length=30)
address = models.CharField("地址", max_length=50)
city = models.CharField("城市", max_length=60)
state_province = models.CharField("省份", max_length=30)
country = models.CharField("国家", max_length=50)
website = models.URLField("网址") class Meta:
verbose_name = '出版商'
verbose_name_plural = verbose_name def __str__(self):
return self.name

urls.py里加入如下配置:

url(r'^add_publisher/$', views.add_publisher, name='add_publisher'),

一下代码着重介绍模版文件的编写和views.py文件的编写

html文件:\hello_django\hello\templates\add_publisher.html

views.py文件:\hello_django\hello\views.py

1.不使用Django组件进行提交

和普通的html提交没什么不同,后台views.py使用命令一个一个的接収参数,然后进行处理,需要自己进行数据校验,自己进行组装数据

html文件:自己写form表单

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加出版社信息</title>
</head>
<body>
<form action="{% url 'add_publisher' %}" method="post">
{% csrf_token %}
名称:<input name="name" type="text" /><br>
地址:<input name="address" type="text" /><br>
城市:<input name="city" type="text" /><br>
省份:<input name="state_province" type="text" /><br>
国家:<input name="country" type="text" /><br>
网址:<input name="website" type="text" /><br>
<input type="submit" value="提交"><br>
</form>
</body>
</html>

views.py(自己接受数据,自己组装数据)

def add_publisher(request):
if request.method == "POST":
name = request.POST['name']
address = request.POST.get('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,
country = country,
website = website,
)
return HttpResponse("添加出版社信息成功!")
else:
return render(request, 'add_publisher.html', locals())

2.使用django.forms.Form(所有表单类的父类)进行提交

新建\hello_django\hello\forms.py文件,参数是forms.Form标识他是一个Form的子类

from django import forms

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

html文件:这样不用自己写表单了

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加出版社信息</title>
</head>
<body>
<form action="{% url 'add_publisher' %}" method="post">
{% csrf_token %}
{{ publisher_form.as_p }}
<input type="submit" value="提交"><br>
</form>
</body>
</html>

views.py文件:不用一个一个接受参数,也不用自己做参数校验了

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['name'],
address = publisher_form.cleaned_data['address'],
city = publisher_form.cleaned_data['city'],
state_province = publisher_form.cleaned_data['state_province'],
country = publisher_form.cleaned_data['country'],
website = publisher_form.cleaned_data['website'],
)
return HttpResponse("添加出版社信息成功!")
else:
publisher_form = PublisherForm()
return render(request, 'add_publisher.html', locals())

3.使用django.forms.ModelForm(可以和模型绑定的Form)进行提交

新建\hello_django\hello\forms.py文件,参数是forms.ModelForm标识他是一个ModelForm的子类

  from django import forms
  from hello.models import Publisher   class PublisherForm(forms.ModelForm):
   class Meta:
   model = Publisher
   exclude = ("id",) views.py文件:不用一个一个接受参数,也不用自己做参数校验了,也不同自己创建对象
  def add_publisher(request):
  if request.method == "POST":
  publisher_form = PublisherForm(request.POST)
  if publisher_form.is_valid():
   publisher_form.save()
  return HttpResponse("添加出版社信息成功!")
  else:
  publisher_form = PublisherForm()
  return render(request, 'add_publisher.html', locals())

												

16.Django提交表单的更多相关文章

  1. Django提交表单时遇到403错误:CSRF verification failed

    这个问题是由跨站点伪造请求(CRSF)造成的,要彻底的弄懂这个问题就要理解什么是CRSF,以及Django提供的CSRF防护机制是怎么工作的. 什么是CSRF CSRF, Cross Site Req ...

  2. Django报错:提交表单报错---RuntimeError: You called this URL via POST, but the URL doesn’t end in a slash and you have APPEND_SLASH set.

    Django报错:提交表单报错---RuntimeError: You called this URL via POST, but the URL doesn’t end in a slash and ...

  3. Django:提交表单报错:RuntimeError: You called this URL via POST, but the URL doesn’t end in a slash and you have A

    Django:提交表单报错:RuntimeError: You called this URL via POST, but the URL doesn’t end in a slash and you ...

  4. 4 django系列之HTML通过form标签来同时提交表单内容与上传文件

    preface 我们知道提交表单有2种方式,一种直接通过submit页面刷新方法来提交,另一种通过ajax异步局部刷新的方法提交,上回我们说了通过ajax来提交文件到后台,现在说说通过submit来提 ...

  5. Django:提交表单时遇到403错误:CSRF verification failed

    Django:提交表单时遇到403错误:CSRF verification failed 问题: 提交表单时遇到403错误:CSRF verification failed 解决方案: 在表单界面ht ...

  6. Django ajax方法提交表单,及后端接受数据

    前台代码: {% block content %} <div class="wrapper wrapper-content"> <div class=" ...

  7. 搭建简单Django服务并通过HttpRequester实现GET/POST http请求提交表单

    调试Django框架写的服务时,需要模拟客户端发送POST请求,然而浏览器只能模拟简单的GET请求(将参数写在url内),网上搜索得到了HttpRequester这一firefox插件,完美的实现了模 ...

  8. Django---静态文件配置,post提交表单的csrf问题(日后细说),创建app子项目和分析其目录,ORM对象关系映射简介,Django操作orm(重点)

    Django---静态文件配置,post提交表单的csrf问题(日后细说),创建app子项目和分析其目录,ORM对象关系映射简介,Django操作orm(重点) 一丶Django的静态文件配置 #we ...

  9. django from表单验证

    django from表单验证   实现:表单验证 工程示例: urls.py 1 2 3 4 5 6 7 8 9 from django.conf.urls import url from djan ...

随机推荐

  1. JAVA Eclipse 启动 Eclipse 弹出“Failed to load the JNI shared library jvm_dll”怎么办

    原因1:给定目录下jvm.dll不存在. 对策:(1)重新安装jre或者jdk并配置好环境变量.(2)copy一个jvm.dll放在该目录下. 原因2:eclipse的版本与jre或者jdk版本不一致 ...

  2. epoll使用详解(精髓)(转)

    epoll - I/O event notification facility 在linux的网络编程中,很长的时间都在使用select来做事件触发.在linux新的内核中,有了一种替换它的机制,就是 ...

  3. 2015级C++第7周项目 友元、共享数据保护、多文件结构

    [项目1-成员函数.友元函数和一般函数有差别]參考解答 (1)阅读以下的程序,体会凝视中的说明(要执行程序,请找到课程主页并复制代码) //例:使用成员函数.友元函数和一般函数的差别 #include ...

  4. Hive命令行经常使用操作(数据库操作,表操作)

    数据库操作 查看全部的数据库 hive> show databases ; 使用数据库default hive> use default; 查看数据库信息 hive > descri ...

  5. lua连接数据库之luasql ------ luasql连接mysql数据库 及 luasql源码编译

    lua连接数据库不只luasql这个库,但目前更新最快的的貌似是这个luasql,他是开源的,支持的数据库功能如下: Connect to ODBC, ADO, Oracle, MySQL, SQLi ...

  6. Spring 应用外部属性文件 配置 context 错误

    在Spring配置文件中出现通配符的匹配很全面, 但无法找到元素 'context:property-placeholder' 的声明这个错误,其实主要是我们在引入命名空间时没有正确引入它的DTD解析 ...

  7. different between method and function

    A method is on an object. A function is independent of an object. For Java, there are only methods. ...

  8. 标准库 - 输入输出处理(input and output facilities) lua

    标准库 - 输入输出处理(input and output facilities)责任编辑:cynthia作者:来自ITPUB论坛 2008-02-18 文本Tag: Lua [IT168 技术文档] ...

  9. Springboot Maven 多模块项目中 @Service跨模块引用失败的问题

    子模块中引用另一个子模块中的Service, @Autowired失败. 添加了模块之间的依赖没解决. 组以后在启动类上加上 @SpringBootApplication(scanBasePackag ...

  10. u-boot-2014_04在TQ2440上的移植

    本文详细介绍了新版本的u-boot-2014_04在tq2440平台上的移植过程,期间参考了网上的其他移植文档,还有韦东山的移植uboot视频,讲的很好.下面是共享链接,欢迎下载,一同学习.其中有移植 ...