上一篇: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),
]
最后的展示結果如下:

