A reusable Django application for simple tagging with comprehensive manager and form support.
npx @tessl/cli install tessl/pypi-django-taggit@6.1.0A comprehensive Django application for simple tagging functionality. Django-taggit provides a TaggableManager that can be easily integrated into Django models to add tagging capabilities, allowing developers to associate multiple tags with model instances through a clean and intuitive API. It supports common tagging operations, automatic tag normalization and deduplication, built-in admin interface integration, and form widgets for tag input.
pip install django-taggitfrom taggit.managers import TaggableManagerCommon imports for various components:
from taggit.models import Tag, TaggedItem
from taggit.forms import TagField, TagWidget
from taggit.admin import TagAdmin
from taggit.utils import parse_tags, edit_string_for_tagsfrom django.db import models
from taggit.managers import TaggableManager
class Food(models.Model):
name = models.CharField(max_length=100)
tags = TaggableManager()
# Usage in application code
apple = Food.objects.create(name="apple")
# Add tags
apple.tags.add("red", "green", "delicious")
# Get all tags
all_tags = apple.tags.all()
tag_names = apple.tags.names()
# Filter objects by tag
red_foods = Food.objects.filter(tags__name="red")
# Remove tags
apple.tags.remove("green")
# Clear all tags
apple.tags.clear()
# Set tags (replace all existing tags)
apple.tags.set(["fresh", "organic", "fruit"])Django-taggit uses a flexible architecture built around several key components:
This design allows tagging to be added to any Django model with a single field, while providing comprehensive functionality for tag management, querying, and administration.
Core functionality for adding tagging capabilities to Django models using the TaggableManager field, including configuration options and basic tag operations.
class TaggableManager:
def __init__(
self,
verbose_name="Tags",
help_text="A comma-separated list of tags.",
through=None,
blank=False,
related_name=None,
to=None,
ordering=None,
manager=None
): ...Methods for adding, removing, querying, and managing tags on model instances, including bulk operations and advanced querying capabilities.
def add(*tags, through_defaults=None, tag_kwargs=None, **kwargs): ...
def remove(*tags): ...
def clear(): ...
def set(tags, *, through_defaults=None, **kwargs): ...
def names(): ...
def most_common(min_count=None, extra_filters=None): ...Form fields and widgets for handling tag input in Django forms, including validation and display customization.
class TagField(forms.CharField):
widget = TagWidget
def clean(self, value): ...
class TagWidget(forms.TextInput): ...
class TextareaTagWidget(forms.Textarea): ...Django admin integration for managing tags, including inline editing, search functionality, and tag merging capabilities.
class TagAdmin(admin.ModelAdmin):
list_display = ["name", "slug"]
search_fields = ["name"]
actions = ["render_tag_form"]
class TaggedItemInline(admin.StackedInline):
model = TaggedItemDjango REST framework serializers and fields for handling tags in API endpoints.
class TagListSerializerField(serializers.ListField):
def to_internal_value(self, value): ...
def to_representation(self, value): ...
class TaggitSerializer(serializers.Serializer):
def create(self, validated_data): ...
def update(self, instance, validated_data): ...Generic view components for creating tag-filtered list views and displaying objects by tag.
def tagged_object_list(request, slug, queryset, **kwargs):
"""
Generic view function for listing objects with specific tag.
Parameters:
- request: HTTP request object
- slug: Tag slug to filter by
- queryset: Model queryset to filter
- **kwargs: Additional view parameters
Returns:
HTTP response with filtered object list
"""
class TagListMixin:
"""
Mixin for views filtering objects by tag.
Provides tag-based filtering functionality for
class-based views, particularly ListView.
"""
tag_suffix = "_tag"
def dispatch(self, request, *args, **kwargs): ...
def get_queryset(self, **kwargs): ...
def get_template_names(self): ...
def get_context_data(self, **kwargs): ...Utility functions for tag parsing and formatting, plus management commands for maintaining tag data integrity.
def parse_tags(tagstring): ...
def edit_string_for_tags(tags): ...
# Management commands
# python manage.py remove_orphaned_tags
# python manage.py deduplicate_tagsclass Tag(models.Model):
"""Individual tag with name and slug."""
name = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True, allow_unicode=True)
def save(self, *args, **kwargs): ...
def slugify(self, tag, i=None): ...
class TaggedItem(models.Model):
"""Links tags to any Django model via generic foreign key."""
tag = models.ForeignKey(Tag, on_delete=models.CASCADE)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.IntegerField(db_index=True)
content_object = GenericForeignKey()
# Base classes for custom implementations
class TagBase(models.Model):
"""
Abstract base class for custom tag models.
Provides core functionality including name, slug, natural key support,
and automatic slug generation from name.
"""
name = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True, allow_unicode=True)
def __str__(self): ...
def __gt__(self, other): ...
def __lt__(self, other): ...
def save(self, *args, **kwargs): ...
def slugify(self, tag, i=None): ...
class ItemBase(models.Model):
"""
Abstract base class for all tagged item relationships.
Provides natural key support and common methods for
tag relationship models.
"""
def __str__(self): ...
@classmethod
def tag_model(cls): ...
@classmethod
def tag_relname(cls): ...
@classmethod
def lookup_kwargs(cls, instance): ...
@classmethod
def tags_for(cls, model, instance=None, **extra_filters): ...
class TaggedItemBase(ItemBase):
"""
Abstract base class for direct foreign key tagged item models.
Use when you want a direct ForeignKey relationship to tags
instead of generic foreign keys.
"""
tag = models.ForeignKey(Tag, related_name="%(app_label)s_%(class)s_items")
class CommonGenericTaggedItemBase(ItemBase):
"""
Abstract base class for generic tagged item models.
Provides the generic foreign key relationship without
specifying the object_id field type.
"""
tag = models.ForeignKey(Tag, on_delete=models.CASCADE, related_name="%(app_label)s_%(class)s_items")
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
content_object = GenericForeignKey('content_type', 'object_id')
class GenericTaggedItemBase(CommonGenericTaggedItemBase):
"""
Abstract base for generic tagged items with integer object_id.
Use for models with integer primary keys (most common case).
"""
object_id = models.IntegerField(db_index=True)
class GenericUUIDTaggedItemBase(CommonGenericTaggedItemBase):
"""
Abstract base for generic tagged items with UUID object_id.
Use for models with UUID primary keys.
"""
object_id = models.UUIDField(db_index=True)
# App Configuration
class TaggitAppConfig(BaseConfig):
"""
Django app configuration for the taggit package.
Configures default settings and app metadata for django-taggit.
"""
name = "taggit"
verbose_name = "Taggit"
default_auto_field = "django.db.models.AutoField"