Django Tagging

November 22, 2009

Django has built in tagging functionality. You can add tags to a model, and then manipulate them in common ways.

from tagging.fields import TagField

# add this to the model
tags = TagField()

def tag_words(self):
    return self.tags.split(' ')


To show tags from a django template

<p class="tags">Tags: 
{% for tag in object.tag_words %}
<a href="/tags/{{tag}}/">{{tag}}</a> 

To show a list of all tags that are for Blog entries marked as live, and also any tags for the Link model. The resulting list is sorted into alphabetical order before being passed to the template

lBlogTags = Tag.objects.usage_for_model(Blog, filters={'status':Blog.LIVE_STATUS})
lLinkTags = Tag.objects.usage_for_model(Link)
lTags = {}
for tag in lBlogTags:
    lTags[] = tag
for tag in lLinkTags:
    lTags[] = tag 
lItems = lTags.items()
lSortedTags = [value for key, value in lItems]

return render_auth(request, 'tags/tag_list.html', {
                                                     'BlogTags' : lBlogTags,
                                                     'LinkTags' : lLinkTags,
                                                     'Tags' : lSortedTags,

To show details of a particular tag

    lTag = Tag.objects.filter(name=pTagName)[0]
except IndexError:
    raise Http404()
lTaggedItems = TaggedItem.objects.filter(tag=lTag)
return render_auth(request, 'tags/tag_detail.html', {'TaggedItems' : lTaggedItems,
                                                     'TagName' : pTagName})

Tags: django tagging