首页 > 解决方案 > Django html页面不显示我在视图中传递的变量

问题描述

我是 Django 的初学者,我遇到了一个问题。我编写了一个代码,允许我从管理员添加不同的产品和类别,然后将它们显示在 html 页面上。但是,当我单击任何显示的产品时,我希望我的产品描述显示在另一个 html 页面中。第一个页面工作得很好(product_list.html),但是我在第二个页面(product_detail.html)上遇到了问题。

urls.py(没有导入):

urlpatterns = [
    url(r'^category/(?P<categoryid>\d+)/$', views.product_list, name='product_list_by_category'),
    #url(r'^list/(?P<id>\d+)/$', views.product_detail, name='product_detail'),
    re_path('^$', views.product_list, name = 'product_list'),
    url(r'^list/(?P<id>\d+)/$', views.product_detail, name='product_detail'),
]

视图.py

def product_list(request, categoryid = 1): *this one is working*

    categories = Category.objects.all()
    products =  Product.objects.all().filter(category_id=categoryid)
    context = {'categories': categories,
               'products': products
               }
    return render(request, 'shop/product_list.html', context)

def product_detail(request, id=1): *this one is not displaying anything*
    productt = Product.objects.all().filter(id = id)
    return render(request, 'shop/product_detail.html', {'product': productt})

product_detail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
       <a href="http://localhost:8000/shop/list/{{product.id}}/">{{product.description}}</a>
</body>
</html>

您知道为什么 product_detail 呈现的页面不显示任何内容吗?

标签: pythonhtmldjangodisplay

解决方案


filter返回一个查询集。查询集没有iddescription属性。

您需要使用get来获取实例:

productt = Product.objects.get(id=id)

推荐阅读