Login

Random code tag

Author:
aaloy
Posted:
July 14, 2007
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.