django-tagging: A Generic Tagging Application for Django Projects

Tagging content is a method for easy classification. It is used on blogs and email alike in order to enable easier search and finding of related content. Tagging support for Django is provided by django-tagging.


At its core, django-tagging allows tags to be stored on Models. It provides a lot of operations with regards to tags, from tag input parsing, retrieval by tags to tag cloud generation. django-tagging can be found here.

The tagging.fields.TagField is a model field that is a CharField that works as the model’s relationship to Tag objects. Correct tag input syntax in django-tagging is by default space-separated unless a comma is present, in which case it becomes comma-separated. Tags can be quoted in order to escape tags containing the separator or just for readability.

Suppose we had the following class Item with a tags field:

import tagging
class Item(models.Model):
    name = models.CharField()
    tags = tagging.fields.TagField()

We create a few Item entries:

>>> Item.objects.create(name='item1', tags='apple banana')
>>> Item.objects.create(name='item2', tags='banana, pineapple')
>>> Item.objects.create(name='item3', tags='apple "soy milk"')

We could retrieve items based on given tags:

>>> from tagging.models import TaggedItem
>>> TaggedItem.objects.get_by_model(Item, 'apple')
[<Item: item1>, <Item: item3>]
>>> TaggedItem.objects.get_by_model(Item, 'apple banana')
[<Item: item1>]

Or we could do the reverse and get the tags of an item:

>>> Tag.objects.get_for_object(Item.objects.get(name='item3'))
[<Tag: apple>, <Tag: soy milk>]

And because we put a TagField in our model, the tags field can be edited in the Django admin site. In fact, any ModelForm based on Item will have a tagging.forms.TagField that validates its input for correct tag syntax.

There is a lot more to django-tagging than what I have described here. There is even a way to use it through using a method to register your Model without having to add a tags field explicitly. And there are also the template and tag cloud generation. Be sure to check out the documentation for all the rest of the features.