我正在开发我的个人博客;它只有两个类别,我想为这两个类别提供一个特定的帖子列表。
出于这个原因,我扩展了get_absolute_url,如下所示:
from django.db import models
from django.urls import reverse
CATEGORY_CHOICES = (
('G.I.S.', 'G.I.S.'),
('Sustainable Mobility', 'Sustainable Mobility'),
)
class Blog(models.Model):
"""
Blog's post definition
"""
title = models.CharField(
max_length=70,
unique=True,
)
slug = models.SlugField(
unique=True,
)
contents = models.TextField()
publishing_date = models.DateTimeField()
category = models.CharField(
max_length=50,
choices=CATEGORY_CHOICES,
)
def __str__(self):
return self.title
def get_absolute_url(self):
if Blog.objects.filter(category="G.I.S."):
return reverse("gis_single_post", kwargs={"slug": self.slug})
if Blog.objects.filter(category="Sustainable Mobility"):
return reverse("sumo_single_post", kwargs={"slug": self.slug})
下面你可以看到views.py;它具有基于类别的不同模型:
from django.shortcuts import render
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from .models import Blog
class GisSinglePost(DetailView):
model = Blog
queryset = Blog.objects.filter(category="G.I.S.")
context_object_name = 'post'
template_name = "gis_single_post.html"
class GisListPost(ListView):
model = Blog
queryset = Blog.objects.filter(category="G.I.S.")
context_object_name = 'posts'
template_name = "gis_list_post.html"
class SuMoSinglePost(DetailView):
model = Blog
queryset = Blog.objects.filter(category="Sustainable Mobility")
context_object_name = 'post'
template_name = "sumo_single_post.html"
class SuMoListPost(ListView):
model = Blog
queryset = Blog.objects.filter(category="Sustainable Mobility")
context_object_name = 'posts'
template_name = "sumo_list_post.html"
下面是urls.py及其四个路径:
from django.urls import include, path
from .views import GisSinglePost, GisListPost, SuMoListPost, SuMoSinglePost
urlpatterns = [
path("gis/", GisListPost.as_view(), name="gis_list_post"),
path("gis/<slug:slug>/", GisSinglePost.as_view(), name="gis_single_post"),
path("sustainable-mobility/", SuMoListPost.as_view(), name="sumo_list_post"),
path("sustainable-mobility/<slug:slug>/", SuMoSinglePost.as_view(), name="sumo_single_post"),
]
当我单击 GIS 类别的单个帖子时,它会毫无问题地显示相关详细信息。但是当我点击另一个类别的帖子时,它会显示给我:
找不到页面 (404) 请求方法:GET 请求 URL: http: //127.0.0.1 :8000/gis/erova-mobilita/ 发起者:blog.views.GisSinglePost
未找到与查询匹配的 Articolo
您看到此错误是因为您的 Django 设置文件中有 DEBUG = True 。将其更改为 False,Django 将显示标准 404 页面。
我已经被这个问题困扰了很多天。我该如何解决?