【问题标题】:Add django-filter to class-based-view to allow user filter results on frontend将 django-filter 添加到基于类的视图以允许用户在前端过滤结果
【发布时间】:2016-03-17 19:23:20
【问题描述】:

不幸的是,Django 没有超级神奇的 Drupal 模拟视图模块 https://www.drupal.org/project/views(顺便说一下,其他 cms 也没有)所以我们都需要在代码中编写视图并添加内容过滤器,就像每个人在 Django 中看到的一样手动管理。

我需要在基于类的视图中为 Charfield 和 datepopup 小部件添加带有下拉列表的过滤器,我发现 django-filter 用于此 http://django-filter.readthedocs.org/en/latest/usage.html

但在文档中没有示例如何使用 CBW 进行设置,仅使用功能视图。

views.py:

class VkwallpostListView(ListView):
    model = Vkwallpost
    context_object_name = "vk_list"

    def get_template_names(self):
        return ["vk_list.html"]

    def get_context_data(self, **kwargs):
        articles = Vkwallpost.objects.order_by("-date_created")[:5]
        videos = Fbpagepost.objects.order_by("-date_created")[:5]
        items = list(articles) + list(videos)
        items.sort(key=lambda i: i.date_created, reverse=True)
        return {"vk_fb_list": items[:5]}

    def get_queryset(self):
        wallposts = Vkwallpost.objects
        if 'all_posts' not in self.request.GET:
            pass
        elif 'all' in self.request.GET:
            pass
        else:
            success = False
            criteria = {}
            if 'sentiment' in self.request.GET:
                criteria['sentiment'] = self.request.GET['sentiment']                   
            print(criteria)
            wallposts = wallposts.filter(**criteria)

        return wallposts

我想轻松添加此过滤器:

import django_filters

class VkwallpostFilter(django_filters.FilterSet):
    class Meta:
        model = Vkwallpost
        fields = ['sentiment', 'date_created']

如何做到这一点?

【问题讨论】:

    标签: python django django-filter


    【解决方案1】:

    尝试使用带有ModelChoiceFieldModelMultipleChoiceField 的Django 表单。

    这就是你所需要的。

    【讨论】:

      猜你喜欢
      • 2011-09-20
      • 2021-06-24
      • 2020-06-16
      • 1970-01-01
      • 2018-03-12
      • 2016-05-20
      • 1970-01-01
      • 1970-01-01
      • 2018-11-19
      相关资源
      最近更新 更多