Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hannylicious/416556c8cdb745952d19f4aaf9cb8ea8 to your computer and use it in GitHub Desktop.
Save hannylicious/416556c8cdb745952d19f4aaf9cb8ea8 to your computer and use it in GitHub Desktop.
A simple tag to add attributes to elements in Django
from django import template
register = template.Library()
@register.simple_tag
def add_attr(field, **kwargs):
return field.as_widget(attrs=kwargs)

To use this - add add_attr.py to you your Django project in the templatetags directory.

Structure would look something like this:

  • Project Dir
    • App Dir
      • templatetags
        • add_attr.py

In the view where you want to add an attribute to something - you would load it at the top of the file with

{% load add_attr %}

Useage within the view template:

{% add_attr form.username class='form-control' %}

This adds a class to the form.username element of 'form-control'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment