Django html page does not display a variable i passed in views

纵然是瞬间 提交于 2021-01-29 18:03:24

问题


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 ( without the imports):

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

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>

Do you have any idea why the page rendered by product_detail does not display anything?


回答1:


@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

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

The final option is to use get_object_or_404, which:

Calls get() on a given model manager, but it raises Http404 instead of the model’s DoesNotExist exception.

from django.shortcuts import get_object_or_404

productt = get_object_or_404(Product, id=id)



回答2:


filter returns a queryset. Querysets don't have id or description attributes.

You need to use get to get an instance:

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


来源:https://stackoverflow.com/questions/57994526/django-html-page-does-not-display-a-variable-i-passed-in-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!