如何将函数隐藏到listview?

这是我的代码,我使用 django v3 并希望将 views.py 中的类别函数转换为列表类(ListView)以用于分页。怎么办?万分感谢


urls.py


from django.urls import path from .views import  posts_category

    

    urlpatterns = [

        path('<slug:slug>/', posts_category, name="posts_category"),

    

    ]

model.py


class Category(models.Model):

    parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE)

    title = models.CharField(max_length=70, unique=True)

    slug = models.SlugField(max_length=90, unique=True)

    description = RichTextUploadingField(blank=True, null=True)

    image = models.ImageField(blank=True, upload_to="imgs")

    def __str__(self):

        return self.title

    class MPTTMeta:

        order_insertion_by = ['title']

views.py


def posts_category(request, slug):

    category = Category.objects.all()

    post = Posts.objects.filter(category__slug=slug, status="p")

    context = {

        'category': category,

        'post': post,

    }

    return render(request, 'posts_category.html', context)


波斯汪
浏览 78回答 1
1回答

至尊宝的传说

我不知道在同一页面中显示类别和产品是否是个好主意(从性能的角度来看),但您可以使用以下代码将 FBV 转换为 CBV:from django.views.generic import ListViewclass PostCategoryView(ListView):&nbsp; &nbsp; template_name = 'posts_category.html'&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; def get_queryset(self):&nbsp; &nbsp; &nbsp; &nbsp; slug = self.kwargs.get('slug')&nbsp; &nbsp; &nbsp; &nbsp; return Posts.objects.filter(category__slug=slug, status="p")&nbsp; &nbsp; def get_context_data(self, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; context = super().get_context_data()&nbsp; &nbsp; &nbsp; &nbsp; context['categories'] = Category.objects.all()&nbsp; &nbsp; &nbsp; &nbsp; return context并将您的更改urls为:from django.urls import path&nbsp;from .views import&nbsp; PostCategoryView&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; urlpatterns = [&nbsp; &nbsp; &nbsp; &nbsp; path('<slug:slug>/', PostCategoryView.as_view(), name="posts_category"),&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; ]最后,您可以像下面的代码一样在模板中使用上下文数据:{% for obj in object_list %}&nbsp; &nbsp; {{ obj.id }} - {{ obj.name }}</a><br>&nbsp; &nbsp; {% endfor %}请注意,这object_list是您的 Post 对象的列表,您应该更改obj.name为 Post 模型的其他字段。最后,您可以使用类似的东西object_list(这里我们使用categories)并循环遍历它以显示您的类别或其他内容的数据。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python