None

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.

models.py

from tagging.fields import TagField

# add this to the model
tags = TagField()

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

blog_detail.html

To show tags from a django template

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

views.py

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.name] = tag
for tag in lLinkTags:
    lTags[tag.name] = tag 
lItems = lTags.items()
lItems.sort()
lSortedTags = [value for key, value in lItems]

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

views.py

To show details of a particular tag

try:
    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