Skip to content
Mar 30 / Nizam Sayeed

UUID template tag for Django

A while back, I had posted a template tag on djangosnippets which generates UUIDs on the fly. I figured that I’d share the same snippet here and explain why I did it.

My rationale for writing this: I needed a quick way to generate random IDs to assign to dynamically generated HTML elements and then use jQuery to wire them all up.

from django.template import Library, Node, TemplateSyntaxError
from uuid import uuid4

register = Library()

class UUIDNode(Node):
    Implements the logic of this tag.
    def __init__(self, var_name):
        self.var_name = var_name
    def render(self, context):
        context[self.var_name] = str(uuid4())
        return ''

def do_uuid(parser, token):
    The purpose of this template tag is to generate a random
    UUID and store it in a named context variable.
    Sample usage:
        {% uuid var_name %}
        var_name will contain the generated UUID
        tag_name, var_name = token.split_contents()
    except ValueError:
        raise TemplateSyntaxError, "%r tag requires exactly one argument" % token.contents.split()[0]
    return UUIDNode(var_name)

do_uuid = register.tag('uuid', do_uuid)