A reusable Django application for simple tagging with comprehensive manager and form support.
npx @tessl/cli install tessl/pypi-django-taggit@6.1.00
# Django Taggit
1
2
A 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.
3
4
## Package Information
5
6
- **Package Name**: django-taggit
7
- **Language**: Python
8
- **Installation**: `pip install django-taggit`
9
- **Django Versions**: 4.1+
10
- **Python Versions**: 3.8+
11
12
## Core Imports
13
14
```python
15
from taggit.managers import TaggableManager
16
```
17
18
Common imports for various components:
19
20
```python
21
from taggit.models import Tag, TaggedItem
22
from taggit.forms import TagField, TagWidget
23
from taggit.admin import TagAdmin
24
from taggit.utils import parse_tags, edit_string_for_tags
25
```
26
27
## Basic Usage
28
29
```python
30
from django.db import models
31
from taggit.managers import TaggableManager
32
33
class Food(models.Model):
34
name = models.CharField(max_length=100)
35
tags = TaggableManager()
36
37
# Usage in application code
38
apple = Food.objects.create(name="apple")
39
40
# Add tags
41
apple.tags.add("red", "green", "delicious")
42
43
# Get all tags
44
all_tags = apple.tags.all()
45
tag_names = apple.tags.names()
46
47
# Filter objects by tag
48
red_foods = Food.objects.filter(tags__name="red")
49
50
# Remove tags
51
apple.tags.remove("green")
52
53
# Clear all tags
54
apple.tags.clear()
55
56
# Set tags (replace all existing tags)
57
apple.tags.set(["fresh", "organic", "fruit"])
58
```
59
60
## Architecture
61
62
Django-taggit uses a flexible architecture built around several key components:
63
64
- **TaggableManager**: A Django field that provides tagging functionality to any model
65
- **Tag Model**: Stores individual tag names and slugs with natural key support
66
- **TaggedItem Model**: Links tags to any Django model using generic foreign keys
67
- **Manager Classes**: Handle tag operations, queries, and prefetching
68
- **Form Integration**: Provides form fields and widgets for tag input in Django forms
69
- **Admin Integration**: Built-in admin interface with tag management and merging capabilities
70
71
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.
72
73
## Capabilities
74
75
### Model Integration
76
77
Core functionality for adding tagging capabilities to Django models using the TaggableManager field, including configuration options and basic tag operations.
78
79
```python { .api }
80
class TaggableManager:
81
def __init__(
82
self,
83
verbose_name="Tags",
84
help_text="A comma-separated list of tags.",
85
through=None,
86
blank=False,
87
related_name=None,
88
to=None,
89
ordering=None,
90
manager=None
91
): ...
92
```
93
94
[Model Integration](./model-integration.md)
95
96
### Tag Operations
97
98
Methods for adding, removing, querying, and managing tags on model instances, including bulk operations and advanced querying capabilities.
99
100
```python { .api }
101
def add(*tags, through_defaults=None, tag_kwargs=None, **kwargs): ...
102
def remove(*tags): ...
103
def clear(): ...
104
def set(tags, *, through_defaults=None, **kwargs): ...
105
def names(): ...
106
def most_common(min_count=None, extra_filters=None): ...
107
```
108
109
[Tag Operations](./tag-operations.md)
110
111
### Form Integration
112
113
Form fields and widgets for handling tag input in Django forms, including validation and display customization.
114
115
```python { .api }
116
class TagField(forms.CharField):
117
widget = TagWidget
118
def clean(self, value): ...
119
120
class TagWidget(forms.TextInput): ...
121
class TextareaTagWidget(forms.Textarea): ...
122
```
123
124
[Form Integration](./form-integration.md)
125
126
### Admin Interface
127
128
Django admin integration for managing tags, including inline editing, search functionality, and tag merging capabilities.
129
130
```python { .api }
131
class TagAdmin(admin.ModelAdmin):
132
list_display = ["name", "slug"]
133
search_fields = ["name"]
134
actions = ["render_tag_form"]
135
136
class TaggedItemInline(admin.StackedInline):
137
model = TaggedItem
138
```
139
140
[Admin Interface](./admin-interface.md)
141
142
### REST Framework Integration
143
144
Django REST framework serializers and fields for handling tags in API endpoints.
145
146
```python { .api }
147
class TagListSerializerField(serializers.ListField):
148
def to_internal_value(self, value): ...
149
def to_representation(self, value): ...
150
151
class TaggitSerializer(serializers.Serializer):
152
def create(self, validated_data): ...
153
def update(self, instance, validated_data): ...
154
```
155
156
[REST Framework Integration](./rest-framework.md)
157
158
### View Helpers
159
160
Generic view components for creating tag-filtered list views and displaying objects by tag.
161
162
```python { .api }
163
def tagged_object_list(request, slug, queryset, **kwargs):
164
"""
165
Generic view function for listing objects with specific tag.
166
167
Parameters:
168
- request: HTTP request object
169
- slug: Tag slug to filter by
170
- queryset: Model queryset to filter
171
- **kwargs: Additional view parameters
172
173
Returns:
174
HTTP response with filtered object list
175
"""
176
177
class TagListMixin:
178
"""
179
Mixin for views filtering objects by tag.
180
181
Provides tag-based filtering functionality for
182
class-based views, particularly ListView.
183
"""
184
tag_suffix = "_tag"
185
186
def dispatch(self, request, *args, **kwargs): ...
187
def get_queryset(self, **kwargs): ...
188
def get_template_names(self): ...
189
def get_context_data(self, **kwargs): ...
190
```
191
192
[View Helpers](./view-helpers.md)
193
194
### Utilities and Management
195
196
Utility functions for tag parsing and formatting, plus management commands for maintaining tag data integrity.
197
198
```python { .api }
199
def parse_tags(tagstring): ...
200
def edit_string_for_tags(tags): ...
201
202
# Management commands
203
# python manage.py remove_orphaned_tags
204
# python manage.py deduplicate_tags
205
```
206
207
[Utilities and Management](./utilities-management.md)
208
209
## Types
210
211
```python { .api }
212
class Tag(models.Model):
213
"""Individual tag with name and slug."""
214
name = models.CharField(max_length=100, unique=True)
215
slug = models.SlugField(max_length=100, unique=True, allow_unicode=True)
216
217
def save(self, *args, **kwargs): ...
218
def slugify(self, tag, i=None): ...
219
220
class TaggedItem(models.Model):
221
"""Links tags to any Django model via generic foreign key."""
222
tag = models.ForeignKey(Tag, on_delete=models.CASCADE)
223
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
224
object_id = models.IntegerField(db_index=True)
225
content_object = GenericForeignKey()
226
227
# Base classes for custom implementations
228
class TagBase(models.Model):
229
"""
230
Abstract base class for custom tag models.
231
232
Provides core functionality including name, slug, natural key support,
233
and automatic slug generation from name.
234
"""
235
name = models.CharField(max_length=100, unique=True)
236
slug = models.SlugField(max_length=100, unique=True, allow_unicode=True)
237
238
def __str__(self): ...
239
def __gt__(self, other): ...
240
def __lt__(self, other): ...
241
def save(self, *args, **kwargs): ...
242
def slugify(self, tag, i=None): ...
243
244
class ItemBase(models.Model):
245
"""
246
Abstract base class for all tagged item relationships.
247
248
Provides natural key support and common methods for
249
tag relationship models.
250
"""
251
def __str__(self): ...
252
253
@classmethod
254
def tag_model(cls): ...
255
256
@classmethod
257
def tag_relname(cls): ...
258
259
@classmethod
260
def lookup_kwargs(cls, instance): ...
261
262
@classmethod
263
def tags_for(cls, model, instance=None, **extra_filters): ...
264
265
class TaggedItemBase(ItemBase):
266
"""
267
Abstract base class for direct foreign key tagged item models.
268
269
Use when you want a direct ForeignKey relationship to tags
270
instead of generic foreign keys.
271
"""
272
tag = models.ForeignKey(Tag, related_name="%(app_label)s_%(class)s_items")
273
274
class CommonGenericTaggedItemBase(ItemBase):
275
"""
276
Abstract base class for generic tagged item models.
277
278
Provides the generic foreign key relationship without
279
specifying the object_id field type.
280
"""
281
tag = models.ForeignKey(Tag, on_delete=models.CASCADE, related_name="%(app_label)s_%(class)s_items")
282
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
283
content_object = GenericForeignKey('content_type', 'object_id')
284
285
class GenericTaggedItemBase(CommonGenericTaggedItemBase):
286
"""
287
Abstract base for generic tagged items with integer object_id.
288
289
Use for models with integer primary keys (most common case).
290
"""
291
object_id = models.IntegerField(db_index=True)
292
293
class GenericUUIDTaggedItemBase(CommonGenericTaggedItemBase):
294
"""
295
Abstract base for generic tagged items with UUID object_id.
296
297
Use for models with UUID primary keys.
298
"""
299
object_id = models.UUIDField(db_index=True)
300
301
# App Configuration
302
class TaggitAppConfig(BaseConfig):
303
"""
304
Django app configuration for the taggit package.
305
306
Configures default settings and app metadata for django-taggit.
307
"""
308
name = "taggit"
309
verbose_name = "Taggit"
310
default_auto_field = "django.db.models.AutoField"
311
```