public
Last active

Useful Django templatetag that passes a list of choices from your models.py as a context variable to your templates

  • Download Gist
django-get-options.py
Python
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 35 36 37 38 39 40
'''
This Snippet creates a custom template tag for passing a context variable to your template with a list of choices from your models.py i.e
 
COL_CHOICES =(
(1, 'Not Applicable'),
(2, 'Black'),
)
 
Usage:
1. Save to template tags dir
2. edit to import the choices you want from your models.py
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 myproject.app.models 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)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.