Django html页面未显示我在视图中传递的变量 [英] Django html page does not display a variable i passed in views
问题描述
我是Django的初学者,遇到了一个问题.我编写了一个代码,该代码使我可以从admin添加不同的产品和类别,然后将它们显示在html页面上.但是,当我单击任何显示的产品时,我希望我的产品描述显示在另一个html页面中.第一页工作正常(product_list.html),但是第二页(product_detail.html)却遇到问题.
i am a beginner with Django and i encountered a problem. I wrote a code which allows me to add different products and categories from admin, and then display them on a html page. However, when i click on any of the displayed products i want my product description to be displayed in another html page. The first page is working just fine( product_list.html), however i am having trouble with the second one (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'),
]
views.py
views.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呈现的页面不显示任何内容吗?
Do you have any idea why the page rendered by product_detail does not display anything?
推荐答案
@DanielRoseman是正确的,但是为了防止出现错误,如果没有具有该ID的产品,您可以使用3个选项.第一个是执行查询集并获取第一个元素,然后检查是否有结果,如下所示:
@DanielRoseman is right, but to prevent an error in case there's no Product with that id, you have 3 options. The first one is to do a queryset and get the first element, then check if there is a result, like this:
productt = Product.objects.filter(id=id).first()
if productt is None:
# do something to let the user know the product doesn't exist
第二个选项是将您的 get
方法包装在 try以外的地方
:
The second option is to wrap your get
method arround a try except
:
try:
productt = Product.objects.get(id=id)
except Product.DoesNotExist:
# do something to let the user know the product doesn't exist
最后一个选择是使用get_object_or_404 ,其中:
The final option is to use get_object_or_404, which:
在给定的模型管理器上调用get(),但它引发Http404而不是模型的DidNotExist异常.
Calls get() on a given model manager, but it raises Http404 instead of the model’s DoesNotExist exception.
来自django.shortcuts的
from django.shortcuts import get_object_or_404
productt = get_object_or_404(Product, id=id)
这篇关于Django html页面未显示我在视图中传递的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!