nix1947
10/13/2017 - 1:14 AM

Django templates

django templates snippets

`

{{ form.non_field_errors }}
{{ form.subject.errors }} {{ form.subject.label_tag }} {{ form.subject }} {{ form.subject.help_text }}

`

Hello world

form.subject is an instance of BoundField which has the as_widget method. you can create a custom filter "addclass" in "my_app/templatetags/myfilters.py"

from django import template

register = template.Library()

@register.filter(name='addclass')
def addclass(value, arg):
    return value.as_widget(attrs={'class': arg})
And then apply your filter:

{% load myfilters %}
<form action="/contact/" method="post">
    {{ form.non_field_errors }}
    <div class="fieldWrapper">
        {{ form.subject.errors }}
        {{ form.subject.label_tag }}
        {{ form.subject|addclass:'MyClass' }}
        <span class="helptext">{{ form.subject.help_text }}</span>
    </div>
</form>

form.subjects will then be rendered with the "MyClass" css class.