简体   繁体   中英

How to use Django-Filter together with Django-Taggit (to filter posts by tags)?

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

You can do it by the tags name

class FilterName(django_filters.FilterSet):
    class Meta:
        model = Modelname
        fields = {'tags__name':{'exact'}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM