上一篇:Django之--MVC的Model 演示了如何使用GET方法处理表单请求,本文讲述直接在当前页面返回结果,并使用更常用的POST方法处理。
Post方法与get方法的区别网上有很多这里不再详述,相对来说POST更加安全和用途多样,get多用于不包含敏感信息的查询。
一、首先我们修改下page.html
{{ 标题 }}
{% for 商品 in 商品列表 %}
{{ 商品 }}{% endfor %}
#修改为/product,方法修改为post,我们通过此url展示商品和查询结果{% csrf_token %} #添加1
{{ 结果 }}
#添加2:这里预留一个结果显示行{% 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),
]
最后的展示结果如下: