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
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))
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 %}