Django 使用基于类的视图显示包含slug和Post slug类别的URL

Django 使用基于类的视图显示包含slug和Post slug类别的URL,django,redirect,django-views,django-urls,django-2.1,Django,Redirect,Django Views,Django Urls,Django 2.1,我正在开发一个简单的博客来学习Django。我希望每个帖子都有这样的路径: /1类/职称 /2类/职称 等等 低于url.py from django.urls import include, path from .views import CategoryList, PostList, SingleCategory, SinglePost, SingleTag, TagList urlpatterns = [ path("", PostList.as_view(), na

我正在开发一个简单的博客来学习Django。我希望每个帖子都有这样的路径:

  • /1类/职称
  • /2类/职称
  • 等等
低于url.py

from django.urls import include, path
from .views import CategoryList, PostList, SingleCategory, SinglePost, SingleTag, TagList

urlpatterns = [
        path("", PostList.as_view(), name="list_post"),
        path("<slug:slug>", SinglePost.as_view(), name="single_post"),
        path("tags/", TagList.as_view(), name="list_tag"),
        path("tags/<slug:slug>", SingleTag.as_view(), name="single_tag"),
        path("categories/", CategoryList.as_view(), name="list_category"),
        path("categories/<slug:slug>", SingleCategory.as_view(), name="single_category"),
]
from django.shortcuts import render
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView

from .models import Category, Post, Tag
# Create your views here.

class CategoryList(ListView):
    model = Category
    context_object_name = 'category_list'
    template_name = "list_category.html"


class SingleCategory(DetailView):
    model = Category
    template_name = "single_category.html"


class PostList(ListView):
    model = Post
    queryset = Post.objects.order_by('-id')
    context_object_name = 'post_list'
    template_name = "list_post.html"
    paginate_by = 4


class SinglePost(DetailView):
    model = Post
    template_name = "single_post.html"


class TagList(ListView):
    model = Tag
    context_object_name = 'tag_list'
    template_name = "list_tag.html"


class SingleTag(DetailView):
    model = Tag
    template_name = "single_tag.html"
class Category(models.Model):
    category_name = models.CharField(
                max_length=50,
                )
    slug = models.SlugField(
                unique=True,
                )

    def __str__(self):
        return self.category_name

    def get_absolute_url(self):
        return reverse("single_category", kwargs={"slug": self.slug})


class Post(models.Model):
    title = models.CharField(
                max_length=50,
                )
    slug = models.SlugField(
                unique=True,
                )
    content = models.TextField()
    tag = models.ManyToManyField(
                Tag,
                related_name="tag_set",
                )
    category = models.ForeignKey(
                    Category,
                    on_delete=models.CASCADE,
                    related_name="category_set",
                    )
    highlighted = models.BooleanField(
                    default=False,
                    )

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("single_post", kwargs={"slug": self.slug})

    class Meta:
        ordering = ['-id']
此处models.py

from django.urls import include, path
from .views import CategoryList, PostList, SingleCategory, SinglePost, SingleTag, TagList

urlpatterns = [
        path("", PostList.as_view(), name="list_post"),
        path("<slug:slug>", SinglePost.as_view(), name="single_post"),
        path("tags/", TagList.as_view(), name="list_tag"),
        path("tags/<slug:slug>", SingleTag.as_view(), name="single_tag"),
        path("categories/", CategoryList.as_view(), name="list_category"),
        path("categories/<slug:slug>", SingleCategory.as_view(), name="single_category"),
]
from django.shortcuts import render
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView

from .models import Category, Post, Tag
# Create your views here.

class CategoryList(ListView):
    model = Category
    context_object_name = 'category_list'
    template_name = "list_category.html"


class SingleCategory(DetailView):
    model = Category
    template_name = "single_category.html"


class PostList(ListView):
    model = Post
    queryset = Post.objects.order_by('-id')
    context_object_name = 'post_list'
    template_name = "list_post.html"
    paginate_by = 4


class SinglePost(DetailView):
    model = Post
    template_name = "single_post.html"


class TagList(ListView):
    model = Tag
    context_object_name = 'tag_list'
    template_name = "list_tag.html"


class SingleTag(DetailView):
    model = Tag
    template_name = "single_tag.html"
class Category(models.Model):
    category_name = models.CharField(
                max_length=50,
                )
    slug = models.SlugField(
                unique=True,
                )

    def __str__(self):
        return self.category_name

    def get_absolute_url(self):
        return reverse("single_category", kwargs={"slug": self.slug})


class Post(models.Model):
    title = models.CharField(
                max_length=50,
                )
    slug = models.SlugField(
                unique=True,
                )
    content = models.TextField()
    tag = models.ManyToManyField(
                Tag,
                related_name="tag_set",
                )
    category = models.ForeignKey(
                    Category,
                    on_delete=models.CASCADE,
                    related_name="category_set",
                    )
    highlighted = models.BooleanField(
                    default=False,
                    )

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("single_post", kwargs={"slug": self.slug})

    class Meta:
        ordering = ['-id']
我不明白如何更改“category slug/”中的路径“categories/”。我想对categories/做同样的事情,必须在categories slug/post slug中进行更改


如何使用基于类的视图实现这一点?

您可以在URL中定义任意数量的参数。然后,您需要覆盖
get_object
,以按slug和category获取相关帖子

path('<slug:category_slug>/<slug:post_slug>', SinglePostByCategory.as_view(), 'single_post_by_category')

我已经为addmodels.py编辑了我的帖子。如果我使用您的解决方案,它会显示以下错误:
django.url.exceptions.NoReverseMatch:single_post与关键字参数“{slug':'articolo due'}”相反,找不到。尝试了1种模式:['(?P[-a-zA-Z0-9\]+)\\/(?P[-a-zA-Z0-9\]+)$”
,但我认为问题在于我对Django的技能不强。你能用models.py中的信息回顾一下你过去的帖子吗?这似乎和我的答案一点关系都没有。您是否更改了“单发帖子”URL而不是添加单独的“单发帖子”类别?您是对的!我已经纠正了我的错误,并且我使用了您的路径,只是在视图的名称上有所不同。现在在127.0.0.1:8000中,我遇到了这样一个错误:
django.url.exceptions.NoReverseMatch:single_post'的反向未找到“single_post”不是有效的视图函数或模式名称。
。如果我使用这个路径127.0.0.1:8000/argomento-1/articolo uno(我确信这是正确的),我就有这个错误:
AttributeError:Generic detail view SinglePost必须在URLconf中用对象pk或slug调用。
@DanielRoseman我们是否应该重写get_对象方法而不是get_queryset?我已经重写了这样的get_对象方法:类SinglePostByCategory(DetailView):def get_对象(self,queryset=None):返回get_对象或_404(Post,category_uslug=self.kwargs['category_slug',slug=self.kwargs['Post_slug'])-并且让它很好地工作-我认为您需要更正答案。。。