Login

uuid template tag

Author:
nomadjourney
Posted:
March 7, 2009
Language:
Python
Version:
1.0
Score:
3 (after 3 ratings)

A simple template tag that generates a random UUID and stores it in a name context variable.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
    """
    try:
        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 )

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.