我想将产品 ID 发送到我的视图。
模板
<div class="products__header--search-result">
<ul>
{% for product in products %}
<li onclick="change('{{ product.id }}')"><a href="#">{{ product.name }}</a></li>
{% endfor %}
</ul>
</div>
<script>
function change(foo) {
$.ajax({
url: {% url 'dashboard' %},
data: {
'foo': foo,
},
});
}
</script>
视图.py
myRequets = request.GET.get('foo')
但是 myRequets 返回“无”
我怎样才能解决这个问题?有没有更好的方法将值传递给views.py?
您不需要 JS 来执行此操作,因为 Django 允许在 url 中使用参数:
# URLconf
from django.urls import path
from . import views
urlpatterns = [
path('product/', views.product),
path('product/<int:product_id>/', views.product),
]
视图.py
# View (in product/views.py)
def product(request, product_id=None):
products = None
if product_id:
# Output the appropriate page of product entry, according to product_id.
return ...
# Output the appropriate page when product_id is None
return ...
来源:https : //docs.djangoproject.com/en/3.2/topics/http/urls/#example(改编)
然后在您的模板中:
{% if products %}
<div class="products__header--search-result">
<ul>
{% for product in products %}
<li><a href="/product/{{ product_id }}/">{{ product.name }}</a></li>
{% endfor %}
</ul>
</div>
{% endif %}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句