Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
Useful Django templatetag that passes a list of choices from your as a context variable to your templates
This Snippet creates a custom template tag for passing a context variable to your template with a list of choices from your i.e
(1, 'Not Applicable'),
(2, 'Black'),
1. Save to template tags dir
2. edit to import the choices you want from your
3. Use in the template like: {% get_options your_choices as variable %}
4. You can then do standard for loops in your templates
from django.template import Library, Node
from django.db.models import get_model
# Change this to import the choices you would like
from import MY_CHOICES
class OptionsNode(Node):
def __init__(self, options, varname):
self.options = options
self.varname = varname
def render(self, context):
context[self.varname] = self.options
return ''
def get_options(parser, token):
bits = token.contents.split()
if len(bits) !=4:
raise TemplateSyntaxError, "get_options tag takes exactly Four arguments"
if bits[2] != 'as':
raise TemplateSyntaxError, "Third argument to get_options tag must be 'as'"
if bits[1] == 'COL_CHOICES':
choice = COL_CHOICES
return OptionsNode(choice, bits[3])
get_options = register.tag(get_options)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.