Tags are categories: something that categorizes various pieces into one. For example, a tag python
can have articles related to python. This functionality of tags is needed most in a blog website to organize content.
What is Taggit
in Django
django-taggit is a generic tagging library for Django. It allows the association of multiple tags with any Django model instance and makes retrieval of tags simple. `django-taggit
works with Django 2.2+ and Python 3.6+.
How to install & setup django-taggit
- Step1: Install django-taggit using
pip install django-taggit
- Step2: Add
taggit
to your project’sINSTALLED_APPS
insidesettings.py
. - Step3: Run migrations using
python manage.py makemigrations &&python manage.py migrate
Optional: It always best practice to use virtual environment to install third party libraries. Learn more about virtual environment in python.
How do you use Taggit
Set any model field to TaggableManager
you want enable tagging.
from django.db import models
from taggit.managers import TaggableManager
class Blog(models.Model):
# ... other fields here
tags = TaggableManager()
How to add tags to your post or article from Django admin
In your Django admin, there should be a model named tags

Click Add custom tags, put the tag name, and click on save.

By now, you should have a list of tags created; something like this.

Now when you add your blog post or article, in your tags field type the name of tags you created separated by a comma(,)

That's it for admin.
Other way of creating and adding tags to post it given below:
post = Blog.objects.create(name="how to use taggit")
post.tags.add("python", "django", "ubuntu")
post.tags.all()
[<Tag: python>, <Tag: django>, <Tag: ubuntu>]
post.tags.remove("ubuntu")
post.tags.all()
[<Tag: python>, <Tag: django>]
Blog.objects.filter(tags__name__in=["python"])
[<Blog: post1>, <Blog: post2>]
Is django-taggit
CASE-INSENSITIVE?
By default django-taggit
is CASE-INSENSITIVE, to make it CASE-SENSITIVE set TAGGIT_CASE_INSENSITIVE
to True
in your settings.py
file.
I hope this tutorial helped in adding tags to your Django application. You can check out more python and django tutorials.