首页 > 解决方案 > 找不到页面(404)请求方法:

问题描述

请帮我。我不知道为什么单击产品时看不到产品的详细信息。当我需要在第二个列表(过滤列表)中查看产品详细信息时,两个第一个列表都可以正常工作,显示 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 %}

标签: djangodjango-class-based-views

解决方案


即使您访问/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/<int:pk>/', views.ProductDetailView.as_view(), name='product-detail'),
    path('categories/<category>/', views.ProductListView.as_view(), name='product-list'),
]

然后 for /categories/1,它将与<int:pk>as匹配1,从而触发ProductDetailView


推荐阅读