【发布时间】:2021-02-18 10:57:12
【问题描述】:
我正在使用 django 框架开发我的第一个 eshop 网站,但遇到了一个问题。 我为不同种类的产品(如笔记本电脑、书籍等)创建了一个通用模型。添加到网站的每个产品都可以通过将产品链接到特定类别的外键找到。
问题是我如何才能在laptops.html 上只显示具有指向正确类别的外键的产品?例如,仅显示笔记本电脑类别的产品。 非常感谢您的宝贵时间!
编辑: 在网址中:
urlpatterns=[
path('', views.HomePage.as_view(), name='home'),
path('ComputerScience/', views.ComputerScience.as_view(), name='computer_science'),
path('category/<int:category_pk>/list-products/', views.CompSProd.as_view(), name='category_products_list')]
在computerscience.html 中,我呈现所有类别。 在 views.py 中,我有两个控制器,例如,第一个用于类别,第二个用于笔记本电脑。
views.py
class ComputerScience(ListView):
model = ComputerScienceCategory
template_name = "computer_science.html"
context_object_name = "category"
class CompSProd(ListView):
model = ComputerScienceProducts
template_name = "laptops.html"
context_object_name = "products"
def get_queryset(self):
queryset = super().get_queryset()
# If you wish to still keep the view only for specific category use below line
category = get_object_or_404(ComputerScienceCategory, pk=self.kwargs.get('category_pk'))
queryset = queryset.filter(category=category)
return queryset
这里有我想要显示所有类别的模板。
computer_science.html
<div class="computerScienceContent" id="slide">
{% for cat in category %}
<a href="{% url 'category_products_list' category.pk %} " id="aBar">
<div>
<h4 class="cSh">{{ cat.name }}</h4>
<img src="{{ cat.img.url }}" alt="image" class="img">
</div>
</a>
{% endfor %}
这是笔记本电脑的 html,我想在其中显示整个产品。
laptops.html
{% extends 'index.html' %}
{% block title %}
<title>Laptops</title>
{% endblock %}
{% block cont2 %}
{% endblock %}
我的主要目标是拥有一个页面(computerscience.html),其中我显示了一个包含所有可用类别的列表,当您单击一个类别时,将您重定向到另一个页面,其中列出了所有属于的产品到那个类别。
这是向我抛出的错误:
Reverse for 'category_products_list' with arguments '('',)' not found. 1 pattern(s) tried: ['category/(?P<category_pk>[0-9]+)/list\\-products/$']
【问题讨论】:
标签: python django django-models django-views django-templates