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. The following code represents the urls.py, model.py, view.py, challengePage.html, tag.html
urls.py:
urlpatterns =[
......
path('challengePage/', views.ChallengePage, name ='challengePage'),
path('tag/<str:tag>/', views.tag, name='tag_argument'),
]
The model.py:
class Challenge_code(models.Model): #create a table
auther = models.ForeignKey(User, on_delete = models.CASCADE)
title = models.CharField(max_length = 200, null = False)
body =RichTextUploadingField(blank=True, null=True)
image = models.ImageField(null = True,blank=True ,upload_to='attach/')
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
tags = TaggableManager()
def __str__(self):
return self.title
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=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
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.