如何在链接中传递变量到Django视图 [英] how to Pass variable in link to the django view
问题描述
我有一个HTML表单,该表单使用for循环显示数据.
I have a html form which display data using a for loop.
<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循环在表的第一个列的链接中打印表中的数据.
链接指向一个新页面,我希望在该页面上显示一些数据.
现在,显示的数据是从mongodb数据库动态生成的.我想要当我单击链接时,将值作为参数传递给django视图,因此可以获取包含该参数的数据并在下一页上显示.该怎么做?
This code prints data in a table using a for loop with a link in first colyumn of table.
The link points to a new page where i want some data to be displayed.
Now The displayed data is dynamically generated from a mongodb database. I want when i click on the link it pass the value as a parametre to a django view so can fetch data which contains the parametre and show it on the next page. How to do that?
我的views.py:
My 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, mrp, 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')
推荐答案
首先,建议不要在添加URL时使用html名称.而不是拥有
First of all, its not advisable to use html name when you add a url. Instead of having
href="/product/product.html"
您本来可以拥有类似的东西
you could have just had something like
href="/product/"
因此,在您的urls.py中,应按以下说明对其进行定义
so in your urls.py you should have it defined as below
url(r'^product/$', product),
其中"product"是对应于该请求的视图.
where 'product ' is the corresponding view handling that request.
现在,如果您想从html向django发送一些参数
Now if you want to send some parameters to django from the html
按如下所示呈现您的模板
render your template as below
<tbody id="table">
{% for sku, lid, stk, mrp, sp, stts in product_data %}
<tr>
<td>
<a class="btn-link" href="/product/?sku={{ sku }}">{{sku}}</a>
</td>
<td>{{lid}}</td>
.....
,并且在您看来,即;在产品上
and in your view i.e; at products
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')
这篇关于如何在链接中传递变量到Django视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!