Best way to filter ListView with drop down form in Django

后端 未结 2 869
故里飘歌
故里飘歌 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:23

    In your form, try changing this:

    <option value="{{ author }}">{{ author }}</option>
    

    to this:

    <option value="{{ author.pk }}">{{ author }}</option>
    

    Then, in your view:

    if author_filter:
        result = Post.objects.filter(author_id=int(auth_filter))     
    
    0 讨论(0)
  • 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 %}
        <form action="" method="get">
            {{ filter.form.as_p }}
            <input type="submit" />
        </form>
        {% for obj in filter.qs %}
            {{ obj.name }} - ${{ obj.price }}<br />
        {% endfor %}
    {% endblock %}
    
    0 讨论(0)
提交回复
热议问题