找不到页面(404)请求方法:

Page not found (404) Request Method:

请帮助我。不知道为什么点击商品后看不到商品详情。当我需要在第二个列表(过滤列表)中查看产品详细信息时,第一个列表工作正常,显示 404 错误。 谢谢

下面是我的代码:

我的网址:

from django.urls import path
from . import views

app_name = 'shop'
urlpatterns = [
    path('', views.HomeView.as_view(), name='home'),
    path('categories/<category>/', views.ProductListView.as_view(), name='product-list'),
    path('categories/<int:pk>/', views.ProductDetailView.as_view(), name='product-detail'),
]

观看次数:

from django.shortcuts import render, get_object_or_404, get_list_or_404
from django.views import generic
from .models import Category, Product


class HomeView(generic.ListView):
    model = Category
    template_name = 'home.html'


class ProductListView(generic.ListView):

    template_name = 'product_list.html'

    def get_queryset(self):
        self.category = get_object_or_404(Category, title=self.kwargs['category'])
        return Product.objects.filter(category=self.category)


class ProductDetailView(generic.DetailView):
    model = Product
    template_name = 'product_detail.html'

product_list.html

 {% extends 'base.html' %}
{% load static %}

{% block title %}
    Welcome | Global Market
{% endblock %}

{% block content %}


{% for product in product_list %}
<a href="{% url 'shop:product-detail' product.pk %}">
    <div class="card bg-light mb-3" style="max-width: 18rem;">
        <div class="card-header">{{ product.title }}</div>
        <img class="card-img-top" src="{{ product.image.url }}" alt="{{ product.title }}">
        <div class="card-body">
        <p class="card-text">{{ product.description }}</p>
        </div>
    </div>
</a>
{% endfor %}
{% endblock %}

product_detail.html

{% extends 'base.html' %}
{% load static %}

{% block title %}
    Welcome | Global Market
{% endblock %}

{% block content %}
<h1>thid</h1>

{{ product.name }}
{% endblock %}

即使您访问 /categories/1,它也会使用 ProductListView,因为 str 路径转换器也接受数字序列。您可以交换路径,因此:

from django.urls import path
from . import views

app_name = 'shop'

urlpatterns = [
    path('', views.HomeView.as_view(), name='home'),
    path('categories/<<b>int:pk</b>>/', views.ProductDetailView.as_view(), name='product-detail'),
    path('categories/<<b>category</b>>/', views.ProductListView.as_view(), name='product-list'),
]

然后对于 /categories/1,它将与 <int:pk> 匹配为 1,从而触发 ProductDetailView.