![](/img/trans.png)
[英]How to use Django-Filter together with Django-Taggit (to filter posts by tags)?
[英]How to filter posts by tags using django-taggit in django
目前,我仍在學習 Django 並使用 Django 2.2 創建我的博客。 但不知何故,當我使用 django-taggit 時出現錯誤。
如何通過標簽過濾帖子?
我已經閱讀了文檔,但沒有完全涵蓋如何將其實施到實際項目中。
這是我的代碼:
我嘗試了幾種不同的方法,我仍在從 StackOverflow 搜索,但仍然沒有答案。
從結果/blog/tag/post-tagged
來自相同/blog
。 那么如何從views.py
過濾它呢? 或者也許來自blog.html
?
所以/blog/tag/post-tagged
的結果只來自被標記的帖子。
這是我的代碼:
models.py
:
...
from taggit.managers import TaggableManager
"Post Model"
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
slug = models.SlugField(max_length=100, null=True, blank=True, unique=True)
title = models.CharField(max_length=200)
tags = TaggableManager(blank=True)
...
views.py
:
def blogIndex(request):
posts = Post.objects.all().order_by("-created_date")[0:4]
context = {"posts": posts,}
return render(request, 'blog.html', context)
def Tagging(request, slug):
tags = Tag.objects.filter(slug=slug)
posts = Post.objects.all().order_by("-tags")
context = {
'tags': tags,
'posts': posts,
}
return render(request, 'blog.html', context)
urls.py
:
path("tag/<slug:slug>/", views.Tagging, name='tagged'),
我的blog.html
:
<div id="tags-middle">
<div class="tags-cloud">
Tags :
{% for tag in post.tags.all %}
<a href="{% url 'tagged' tag.slug %}">{{ tag.name }}</a>
{% endfor %}
</div>
</div>
我通過過濾views.py
的標簽解決了這個問題。
因為我的帖子中有多個標簽。 所以__in
和tags
必須在列表中。
這是我的views.py
:
tags = Tag.objects.filter(slug=slug).values_list('name', flat=True)
posts = Post.objects.filter(tags__name__in=tags)
基本上,正如文檔所說,我們可以使用字符串進行過濾,就像:
posts = Post.objects.filter(tags__name__in=["Lorem"])
但它只需要一個字符串。
如果我嘗試使用像["Lorem", "Ipsum"]
這樣的多個字符串["Lorem", "Ipsum"]
它只會在/blog/tag/lorem
上顯示一個空白頁面。
在我的個人博客中,我正在執行以下操作以按標簽過濾帖子:
在urls.py
:
...
path('tag/<tag>', views.tag, name='tag'),
...
views.py
:
from django.shortcuts import render
...
def tag(request, tag):
"This page shows all posts with the related tag"
posts = Post.objects.filter(tags__name=tag)
return render(request, 'blog/tag.html', {'tag': tag, 'posts': posts})
有了這個,你可以有一個blog/tag.html
模板,比如:
<h2>List of posts of the tag "{{ tag }}"</h2>
{% if posts %}
<ul>
{% for post in posts %}
// displays whatever you want about the post
{% endfor %}
</ul>
{% else %}
<p>No post related to that tag yet.</p>
{% endif%}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.