Skip to content

Instantly share code, notes, and snippets.

@hughsaunders
Created May 6, 2012 10:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hughsaunders/2621622 to your computer and use it in GitHub Desktop.
Save hughsaunders/2621622 to your computer and use it in GitHub Desktop.
Django template tag for tabulating model fields.
import re
from django import template
register=template.Library()
class PropertyListNode(template.Node):
def __init__(self,model_string,format_spec):
self.model_string=model_string
self.format_spec=format_spec
def render(self,context):
model_instance=context[self.model_string]
out=""
for field in model_instance.__class__._meta.fields:
try:
out+=self.format_spec%\
(field.verbose_name,
getattr(model_instance,field.name))
except TypeError as e:
raise template.TemplateSyntaxError("invalid format string\
specified to property list template tag: "+str(e))
return out
def property_list(parser,token):
"""Property list tag, returns all fields of a model in the order defined,
using a format specifier passed to the tag.
Example usage {% property_list car
"<li><span>%s:</span><span>%s</span></li>" %}"""
try:
tag_name, model,format_spec=token.split_contents()
#remove quotes from format_spec string
format_spec=re.sub("\"","",format_spec)
except ValueError:
raise template.TemplateSyntaxError("%r tag requires model\
and format string arguments only"%token.contents.split()[0])
return PropertyListNode(model,format_spec)
register.tag('property_list',property_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment