A dynamic template filter for django forms

I used to assign attribute to form controls like this:

class CategoryForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(CategoryForm, self).__init__(*args, **kwargs)
        self.fields['description'].widget.attrs['class'] = 'textarea-medium'

    class Meta:
        model = Category

But this just doesn’t feel right. Wouldn’t it be so much better if we could do this in the template and may be by writing less code?

Okay, here’s my solution:

file: forms_attr.py

from django import template

register = template.Library()

filters = ("id", "class", "size", "name", "max-length")

def filtering(name):

    def fulter(inp, param):
        inp.field.widget.attrs[name] = param
        return inp

    return fulter

for f in filters:
    register.filter(f, filtering(f))

put this file in templatetags folder of your app. And then in the template, first load the filters:

{% load "forms_attr" %}

And enjoy…

 {{ form.description|class:"textarea-medium"|max-length:"200" }}


  • The Earth for our or all

    MuhitJuly 25, 2016

Leave a Reply