# -*- coding: UTF-8 -*- from django import template import string import random register = template.Library() CODE_CHARS = string.ascii_uppercase+string.digits @register.tag(name="randomCode") def randomCode(parser, token): try: # split_contents() knows not to split quoted strings. tag_name, num = token.split_contents() except ValueError: raise template.TemplateSyntaxError, "%r tag requires an integer as a single argument" % token.contents.split()[0] if not (num[0] == num[-1] and num[0] in ('"', "'")): raise template.TemplateSyntaxError, "%r tag's argument should be in quotes and be a positive integer" % tag_name try: value = int(num[1:-1]) if value <0: raise template.TemplateSyntaxError, "%r tag's argument must be a positive integer" except: raise template.TemplateSyntaxError, "%r tag's argument must be a positive integer" % tag_name return randomCodeNode(value) class randomCodeNode(template.Node): def __init__(self, num): self.num = num def render(self, context): try: codi = random.sample(CODE_CHARS,self.num) except ValueError, e: raise template.TemplateSyntaxError, "tag's argument must be a lower than %i" % len(CODE_CHARS) s = '' return s.join(codi)