python - 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 呈现的页面不显示任何内容吗?
解决方案
filter
返回一个查询集。查询集没有id
或description
属性。
您需要使用get
来获取实例:
productt = Product.objects.get(id=id)
推荐阅读
- c++ - 使用数据接口将 C++ 数据存储到八度?
- swift - UIAlertController - 等待用户响应
- python - Y 轴上的次要刻度线未在 matplotlib 中显示
- android - Android dnsjava NoClassDefFoundError:解析失败:Ljava/time/Duration;
- c++ - 如何调用与调用内部类函数同名的外部类函数
- javascript - 使用 totp 进行身份验证和重定向(speakeasy)
- ios - 无法将值传递给另一个类
- python - 考虑到所有类,如何找到所有真阳性、阴性和假阳性和阴性
- python - TypeError: utf_8_encode() 参数 1 必须是 str,而不是 bytes
- amazon-web-services - 如何从 AWS 上的 joomla 网站删除 Bitnami 横幅?