django - 找不到页面(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 %}
解决方案
即使您访问/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
。
推荐阅读
- javascript - Event.target 意外成为绑定事件监听函数中的文档
- rust - 超特征边界中的生命周期参数
- php - Wordpress CF7 从短代码属性中获取下拉列表的所有值
- reactjs - React Native:您是否必须手动升级“project.pbxproj”?
- applescript - 如何使用 Applescript 在 BBEdit 窗口的项目窗格中选择特定文件?解决了
- java - 如何通过java在bash中传递像$(date +“%Y”)这样的命令参数?
- docker - 我应该使用哪些服务来自动构建计算密集型 docker?
- excel - VBA - xlsheetvisible = true 后闪烁
- javascript - JavaScript:有没有办法从字符串创建一个命名的 JSON 对象?
- reactjs - “任务 ':app:packageDebug' 执行失败。” 对于全新的博览会裸工作流应用程序