加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 如何将链接中的变量传递给django视图

发布时间:2020-12-20 12:09:06 所属栏目:Python 来源:网络整理
导读:我有一个html表单,使用for循环显示数据. tbody id="table" {% for sku,lid,stk,mrp,sp,stts in product_data %} tr td a class="btn-link" href="/product/product.html" value="{{sku}}"{{sku}}/a /td td{{lid}}/td ..... 此代码使用for循环在表中打印数据,
我有一个html表单,使用for循环显示数据.

<tbody id="table">
    {% for sku,lid,stk,mrp,sp,stts in product_data %}
    <tr>
        <td>
            <a class="btn-link" href="/product/product.html" value="{{sku}}">{{sku}}</a>
        </td>
        <td>{{lid}}</td>
        .....

此代码使用for循环在表中打印数据,在表的第一个colyumn中有链接.
该链接指向一个新页面,我希望显示一些数据.
现在显示的数据是从mongodb数据库动态生成的.我想当我点击链接时它将值作为参数传递给django视图,因此可以获取包含参数的数据并在下一页显示它.怎么做?

我的views.py:

from django.shortcuts import render
from django.http import HttpResponse
from inventory.models import GetProductData

def inventory(request):
    pd = GetProductData().skuData()
    sku = pd[0]
    listing_id = pd[1]
    stock_count = pd[2]
    mrp = pd[3]
    status = pd[5]
    selling_price = pd[4]

    product_data = zip(sku,listing_id,stock_count,selling_price,status)
    context_dict = {'product_data':product_data}
    return render(request,'inventory/inventory.html',context_dict)

def product(request):
    return render(request,'inventory/product.html')

解决方法

首先,添加网址时不建议使用html名称.而不是拥有

href="/product/product.html"

你可能有类似的东西

href="/product/"

所以在你的urls.py中你应该定义如下

url(r'^product/$',product),

其中’product’是处理该请求的相应视图.

现在,如果你想从html向django发送一些参数

渲染模板如下

<tbody id="table">
    {% for sku,stts in product_data %}
    <tr>
        <td>
            <a class="btn-link" href="/product/?sku={{ sku }}">{{sku}}</a>
        </td>
        <td>{{lid}}</td>
        .....

在你看来,在产品上

def product(request):
    if request.method=='GET':
        sku = request.GET.get('sku')
        if not sku:
            return render(request,'inventory/product.html')
        else:
            # now you have the value of sku
            # so you can continue with the rest
            return render(request,'some_other.html')

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读