【问题标题】:Reverse for 'product' with no arguments not found. 1 pattern(s) tried: ['product\\/(?P<slug>[^/]+)\\/$']未找到没有参数的“产品”反向。尝试了 1 种模式:['product\\/(?P<slug>[^/]+)\\/$']
【发布时间】:2020-05-18 06:49:34
【问题描述】:

我正在尝试建立一个电子商务网站,但由于上面显示的错误,我可以继续。谢谢

url.py 文件

from django.urls import path
from .**views import ItemDetailView, HomeView, checkout

app_name = 'core'

urlpatterns =[
    path('', HomeView.as_view(), name='homepage'),
    path('checkout/', checkout, name='checkout'),
    path('product/<slug>/', ItemDetailView.as_view(), name='product')

views.py 文件

from django.shortcuts import render
from .models import Item
from django.views.generic import ListView, DetailView

class HomeView(ListView):
    model = Item
    template_name = "home-page.html"

class ItemDetailView(DetailView):
    model = Item
    template_name = "product-page.html"

def checkout(request):
    return render(request, 'checkout-page.html')

html模板

<a class="nav-link waves-effect" href="{% url 'core:product' %}" target="_blank">Products</a>

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    您还必须将 slug 传递给模板(在“home-page.html”中)

    {% for product in object_list %}
    <a class="nav-link waves-effect" href="{% url 'core:product' product.slug %}" 
    target="_blank">{{ product.name }}</a>
    {% endfor %}
    

    【讨论】:

    • 我已经做到了,for循环使产品在网页上出现两次,我希望它只出现一次,因为它是一个导航栏
    • 在列表视图中,您将拥有所有产品的列表,如果您想限制它,您可以对查询集进行切片,Item.objects.all()[:1]
    • 在主页视图中添加获取上下文数据的方法。 def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context['object_list'] = Item.objects.all()[:1] return context
    猜你喜欢
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 2020-11-24
    • 2020-10-14
    • 2021-12-20
    • 2020-11-05
    相关资源
    最近更新 更多