Learning Django by Example(7) Attach a tag
Web January 20th, 2008
Tag is probably the most distinguish feature of Web 2.0 applications that differentiate them from the traditional hierarchy categories. I want to attach a Web 2.0 tag to Gelman, so the user could simply click the tag, and find the related books that may arouse his/her interest.
django-taggingis a generic tag application to simplify the backend development, all you need to do is just add the TagField to the Book model:
class Book(models.Model):
……
tags = TagField()
And in the book_detail.html template, refer it as object.tags as this:
popuptags is a custom tag that decorates the tags as a list of HTML links, and join them:
def popuptags(value):
tags = value.split(” “)
return ” “.join([‘<a href="/bookshelf/tags/%s">%s</a>’ % (x, x) for x in tags])
So tag foo is linked with /bookshelf/tags/foo, so just redirect the request to the view:
And handle it in views.py:
def by_tag(request, tag_name):
tag = Tag.objects.get(name=tag_name)
return list_detail.object_list(
request,
queryset=TaggedItem.objects.get_by_model(Book, tag),
template_name=“bookshelf/book_list.html”,
extra_context={‘title’: ‘Tagged by %s’ % tag_name},
)
All the tedious work has been handled by django-tagging: we first get a tag object by name, and then build a QuerySet using get_by_model method; the rest is handled by the generic view, done. Salute to django-tagging developers!
We would discuss how to add a tag in the next post, that is the magic of Dojo.