django-taggit

6.1.0 · active · verified Thu Apr 09

django-taggit is a reusable Django application for simple, yet powerful, tagging. It provides a `TaggableManager` to easily add tags to any Django model. The current version is 6.1.0, and it maintains an active development and release cadence, supporting modern Django and Python versions.

Warnings

Install

Imports

Quickstart

To quickly integrate `django-taggit`, install it, add 'taggit' to your `INSTALLED_APPS`, run migrations, and then add a `TaggableManager` field to your Django model. This example demonstrates basic model creation, tag assignment, filtering, and tag removal.

import os
import django
from django.conf import settings
from django.db import models

settings.configure(
    INSTALLED_APPS=[
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'taggit',
    ],
    DATABASES={
        'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}
    },
    SECRET_KEY=os.environ.get('DJANGO_SECRET_KEY', 'a-very-secret-key-that-should-be-changed'),
    DEFAULT_AUTO_FIELD='django.db.models.BigAutoField',
)
django.setup()

from taggit.managers import TaggableManager

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    tags = TaggableManager()

    def __str__(self):
        return self.title

# --- Example Usage ---

# After migrations (run `python manage.py migrate` in a real project):
# from django.core.management import call_command
# call_command('migrate', interactive=False)

# Create a post
post1 = Post.objects.create(title='My First Post', content='Content goes here.')
post1.tags.add('python', 'django', 'tutorial')

post2 = Post.objects.create(title='Another Post', content='More content.')
post2.tags.add('python', 'web-dev')

print(f"Post 1 tags: {list(post1.tags.names())}")
print(f"Posts tagged with 'python': {Post.objects.filter(tags__name__in=['python']).count()}")
print(f"All tags: {list(TaggableManager().all_tags().names())}")

# Remove a tag
post1.tags.remove('tutorial')
print(f"Post 1 tags after removal: {list(post1.tags.names())}")

view raw JSON →