How can I filter tags with django-taggit
I'm doing the following to filter the posts by tag. But the problem is when clicking the tag button, I do not see any results.
urls.py :
urlpatterns =[
......
path('challengePage/', views.ChallengePage, name ='challengePage'),
path('tag/<tag>', views.tag, name='tag_argument'),
]
the views.py :
def ChallengePage(request):
challenges = Challenge_code.objects.prefetch_related('tags').all().order_by('-created_at')
tags = Tag.objects.all()
context = {
'challenges' : challenges,
'tags':tags,
}
return render(request,'challengePage.html',context)
def tag(request,tag):
challenges_tag = Challenge_code.objects.filter(tags__name__in=tag)
return render(request, 'tag.html',{'tag':tag, 'challenges':challenges_tag})
the challengePage.html :
<div style="text-align: center;">
{% for tag in tags %}
<a href="{% url 'tag_argument' tag %}"><button style="text-align: center;" dir="ltr" class="buttonTag buttonTag2"
> {{tag.name}}</button></a>
{% endfor %}
</div>
the tag.html :
<div class="code_body">
<div class="container_code">
{% for challenge in challenges_tag %}
<div class="Box_code">
<p class="title_code"><bdi style=" color: #000;">
{{challenge.title}}
<br>
{% for tag in challenge.tags.all %}
<small>{{tag}}, </small>
{% endfor %}
</bdi>
</p>
<a href="{% url 'challenge' challenge.id %}"><button class="button1" style="vertical-align:middle"><span>Join</span></button></a>
<p class="name-user">
<bdi>
By:
{{challenge.auther.username}}
</bdi>
</p>
</div>
{% endfor %}
i am using it on my current project i urls.py use
tag/<slug:tag_slug>
in views.py
tag = get_object_or_404(Tag, slug=tag_slug)
query = your_model.filter(tags__in=[tag])
do not forget to import this in your views.py
from taggit.models import Tag
it works very fine with me change it to be suitable for your purpose and i am ready to help but first follow this