realcp1018

上一篇: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),
]

最后的展示结果如下:

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-06-01
  • 2022-12-23
  • 2022-12-23
  • 2022-01-09
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-09
  • 2022-01-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案