Best way to filter ListView with drop down form in Django

后端 未结 2 868
故里飘歌
故里飘歌 2021-02-10 23:57

I\'m trying to filter a ListView based on Users, using a drop down form.

models.py

class Post(models.Model):
    ...
    author = models.ForeignKey(\'aut         


        
2条回答
  •  后悔当初
    2021-02-11 00:27

    Ohh, it is really oldschool, error prone and time consuming way of doing the things.

    Please give a try to django-filter library. And create working fine filters with minimum amount of effort! This allows creating very robust filtering strategies while maintaining clean code.

    https://django-filter.readthedocs.io/en/latest/guide/usage.html#

    below fast draft:

    the filter:

    import django_filters
    
    class PostFilter(django_filters.FilterSet):
        class Meta:
            model = Post
            fields = ['author']
    

    the view:

    from django_filters.views import FilterView
    from somwhere.in.your.project.filtersets import PostFilter
    
    class PostList(FilterView):
        model = Post
        context_object_name = 'posts'
        filter_class = PostFilter
    

    in template:

    {% extends "base.html" %}
    
    {% block content %}
        
    {{ filter.form.as_p }}
    {% for obj in filter.qs %} {{ obj.name }} - ${{ obj.price }}
    {% endfor %} {% endblock %}

提交回复
热议问题