pip install django-taggit==0.17.1
settings.py
INSTALLED_APPS = (
...
'taggit',
)
models.py
from taggit.managers import TaggableManager
class Post(models.Model):
...
tags = TaggableManager()
...
command
python manage.py makemigrations blog
python manage.py migrate blog
shell
from blog.models import Post
post = Post.objects.get(slug='one-more-post')
post.tags.add('music', 'jazz', 'django')
post.tags.all()
post.tags.remove('django')
detail.html
{% with post.tags.all as tags %}
{% for tag in tags %}
{{ tag.name }}
{% endfor %}
{% endwith %}
views.py
from taggit.models import Tag
def post_list(request, tag_slug=None):
...
if tag_slug:
tag = get_object_or_404(Tag, slug=tag_slug)
object_list = object_list.filter(tags__in=[tag])
...
def post_detail(request, year, month, day, slug):
...
post_tags_ids = post.tags.values_list('id', flat=True)
similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)
similar_posts = similar_posts.annotate(
same_tags=Count('tags')).order_by(
'-same_tags', '-publish')[:4]
...