上一篇:Django之--MVC的Model 演示了如何使用GET方法处理表单请求,本文讲述直接在当前页面返回结果,并使用更常用的POST方法处理。

Post方法与get方法的区别网上有很多这里不再详述,相对来说POST更加安全和用途多样,get多用于不包含敏感信息的查询。

一、首先我们修改下page.html

<!DOCTYPE html>
<html>
<h3>{{ 标题 }}</h3>
<body>
<p>
{% for 商品 in 商品列表 %}
<li><font face="verdana" color="blue" size=4>{{ 商品 }}</font></li>
{% endfor %}
</p>
<br>
<form action="/product" method="post"> #修改为/product,方法修改为post,我们通过此url展示商品和查询结果
{% csrf_token %} #添加1
<input type="text" name="q">
<input type="submit" value="查看商品信息">
</form>
<p>{{ 结果 }}</p> #添加2:这里预留一个结果显示行
</body>
</html>

{% csrf_token %}的标签:csrf 全称是 Cross Site Request Forgery。这是Django提供的防止伪装提交请求的功能。POST 方法提交的表格,必须有此标签。

二、然后我们编写product.py文件:

from django.shortcuts import render
from django.views.decorators import csrf
from . import mysql
def page(request):
context={}
context['标题'] ='商品种类:'
pro_list=mysql.db_query("select distinct name from product")
context['商品列表']=[]
for i in range(0,len(pro_list)):
context['商品列表'].append(pro_list[i][0])
if request.POST:
pro=request.POST['q']
if not pro.strip():
context['结果'] = '搜索项不能为空'
else:
price_quan=mysql.db_query("select price,quantity from product where name='%s'"%(pro))
price=str(price_quan[0][0])
quantity=str(price_quan[0][1])
context['结果'] = '你搜索的商品为: ' + pro + '商品价格为:' + price + '商品余量为:' + quantity
return render(request,'page.html',context)

然后这里再贴一下上一篇GET方法的写法作对比:

# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.shortcuts import render
# HttpResponse与render的区别在于,前者只用于返回文本信息,而render即其字面意思“渲染”,意思是使用context渲染html页面后返回。
from . import mysql
# 表单
def page(request):
context={}
context['标题'] ='商品种类:'
pro_list=mysql.db_query("select distinct name from product")
context['商品列表']=[]
for i in range(0,len(pro_list)):
context['商品列表'].append(pro_list[i][0])
return render(request,'page.html',context)
# 接收请求数据
def result(request):
request.encoding='utf-8'
pro=request.GET['q']
if not pro.strip():
message = '搜索项不能为空'
else:
price_quan=mysql.db_query("select price,quantity from product where name='%s'"%(pro))
price=str(price_quan[0][0])
quantity=str(price_quan[0][1])
message = '你搜索的商品为: ' + pro + '商品价格为:' + price + '商品余量为:' + quantity
return HttpResponse(message)

三、最后修改下urls.py

from django.conf.urls import url
from . import view,testdb,search,product urlpatterns = [
url(r'^hello$', view.hello),
url(r'^product$', product.page),
]

最后的展示结果如下:

Django之--POST方法处理表单请求的更多相关文章

  1. 当有多个form表单请求时如何处理?

    问题:当有多个表单请求时如何处理?两种获取form表单 name属性值来区分是哪一个form表单.问题:如何获取name的值呢?<form name="myForm" met ...

  2. Laravel 表单验证创建“表单请求”实现自定义请求类

    按照文档创建表单请求自定义类以后,调用总是403页面,咨询大佬说: public function authorize() { // 在表单验证类的这个方法这里要返回true,默认返回false,这个 ...

  3. jquery 通过submit()方法 提交表单示例

    jquery 通过submit()方法 提交表单示例: 本示例:以用户注册作为例子.使用jquery中的submit()方法实现表单提交. 注:本示例仅提供了对表单的验证,本例只用选用了三个字段作为测 ...

  4. java如何区分是form表单请求,还是ajax请求

    requestType = request.getHeader("X-Requested-With");                 if(requestType==null) ...

  5. MVC中使用内建的HTML辅助方法产生表单元素提交表单与button按钮事件的陷阱

    网站模板页有个登陆的退出按钮,当点击时跳转到登陆页面. <button onclick="logout()" >退出</button> $("#l ...

  6. jQuery form插件的使用--使用 fieldValue 方法校验表单

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <hea ...

  7. 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 ...

  8. Laravel 更新数据时在表单请求验证中排除自己,检查指定字段唯一性

    原文地址:https://moell.cn/article/24 不错的laravel网站 需求场景 修改用户信息时,在表单请求验证中排除当前邮箱所在的记录行,并检查邮箱的唯一性. Laravel版本 ...

  9. 通过C#的HttpClient模拟form表单请求

    post提交表单一般无非是一般text文本和文件类型,如下 <input type="file"/> <input type="text"/& ...

随机推荐

  1. php安装grpc报No releases available for package解决方法

    1.pecl.php.net搜索相应grpc的下载文件,这里找了个stable版本 https://pecl.php.net/get/grpc-1.17.0.tg 2.wge下载+pecl insta ...

  2. C# 委托 事件

    一:什么叫委托 通过反射发现,委托其实是一个类,继承自System.MulticastDelegate,但是System.MulticastDelegate这个类是特殊类,不能被继承 二:委托的声明 ...

  3. [转]js 取得 Unix时间戳(Unix timestamp)

    本文转自:https://blog.csdn.net/o0snow/article/details/6858829 js 取得 Unix时间戳 Unix时间戳(Unix timestamp),或称Un ...

  4. Python多线程的简单实现(生产者消费者模型)

    __author__ = "JentZhang" import time, threading, queue q = queue.Queue(maxsize=) # 声明队列 de ...

  5. 【Mysql】常用命令

    登录mysql -uroot -p 查看有哪些数据库show databases; 创建一个普通用户 sa ,密码是 some_passCREATE USER 'sa'@'%' IDENTIFIED ...

  6. hash 和pushState,replaceState

    hash 要点: 1.不会向后台发请求:#是用来指导浏览器动作的,对服务器端完全无用. 2.用来跳转到页面的指定位置:   为网页位置指定标识符,有两个方法.一是使用锚点,比如<a name=& ...

  7. canvas-8searchLight3.html

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. 精心收集的 48 个 JavaScript 代码片段,仅需 30 秒就可理解!

    原文:https://github.com/Chalarangelo/30-seconds-of-code#anagrams-of-string-with-duplicates 作者:Chalaran ...

  9. 【代码笔记】Web-JavaScript-javaScript for循环

    一,效果图. 二,代码. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...

  10. SAP MM MM17里不能修改物料主数据'Purchasing Value Key'字段值?

    SAP MM MM17里不能修改物料主数据'Purchasing Value Key'字段值? 记得在D项目上线之前数据导入系统之后,业务提出一些物料采购视图里的’Purchasing value k ...