Login

Random code tag

Author:
aaloy
Posted:
July 14, 2007
Language:
Python
Version:
.96
Tags:
tag
Score:
0 (after 2 ratings)

This tag solves for me a simple need: generate random and compact codes for some of my applications. Codes are not guaranteed to be unique.

Usage {% randomCode "num" %}

Example: {% randomCode "8" %} generates a random 8 characters code.

Create a file on your favorite template tags folder called randomcode.py and paste the code.

Don't forget to include {% load randomcode %} in your templates

 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
33
34
# -*- 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)

More like this

  1. uuid template tag by nomadjourney 6 years, 5 months ago
  2. Random-image template tag by pbx 8 years, 5 months ago
  3. Lorem Ipsum - Random content for your mockups by gfranxman 8 years, 6 months ago
  4. LinkShare Pixel Tracking template tag for Satchmo by maxk 4 years, 7 months ago
  5. Generate Model Data. Lots of Options. by bl4th3rsk1t3 5 years, 5 months ago

Comments

Please login first before commenting.