[英]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.