Reputation: 315
I would like to filter my posts by tags. How could I use it together with Django filter? My current situation:
#models.py
from taggit.managers import TaggableManager
class Post(models.Model):
title = models.CharField(max_length = 200)
text = models.TextField(null = True, blank = True)
tags = TaggableManager()
def __str__(self):
return self.title
#forms.py
class PostForm(ModelForm):
class Meta:
model = Post
fields = '__all__'
#filter.py
class PostFilter(django_filters.FilterSet):
class Meta:
model = Post
fields = ['title', 'text']
#views.py
def index(request):
posts = Post.objects.all()
tags = Tag.objects.all()
myFilter = PostFilter(request.GET, queryset=posts)
posts = myFilter.qs
context = {'posts':posts, 'myFilter':myFilter, 'tags':tags}
return render(request, 'posts/index.html', context)
Is there a way to include tags to the forms.py?
edit: added models.py. The "tags" are imported from taggit, but cannot be simply added to the fields in forms.py
Upvotes: 0
Views: 724
Reputation: 35
You can do it by the tags name
class FilterName(django_filters.FilterSet):
class Meta:
model = Modelname
fields = {'tags__name':{'exact'}}
Upvotes: 1