Skip to content

Instantly share code, notes, and snippets.

@kimbo
Last active October 8, 2018 12:22
Show Gist options
  • Save kimbo/adb27ebc49a15576baf625284cd43683 to your computer and use it in GitHub Desktop.
Save kimbo/adb27ebc49a15576baf625284cd43683 to your computer and use it in GitHub Desktop.
Simple django template filters to add attributes to Django form fields
from django import template
register = template.Library()
@register.simple_tag()
def render(field, attrs, val=None):
"""
Renders a form field as a widget with the attributes you specify (separated by commas)
Example usage: {% render field 'class="form-control is-invalid", required' field.value %}
"""
for attr in attrs.split(', '):
x = attr.split('=')
try:
field.field.widget.attrs[x[0]] = x[1].strip('\"')
except IndexError:
field.field.widget.attrs[x[0]] = True
if val is not None:
field.field.widget.attrs['value'] = val
return field.as_widget()
@register.filter()
def add_class(field, classname):
"""
Adds a class to a form field
Example usage: {{ form.field|add_class:'form-control' }}
"""
try:
field.field.widget.attrs['class'] += ' %s' % classname
except KeyError:
field.field.widget.attrs['class'] = classname
return field.as_widget()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment