Define css class in django Forms

前端 未结 13 835
南旧
南旧 2020-11-27 10:11

Assume I have a form

class SampleClass(forms.Form):
    name = forms.CharField(max_length=30)
    age = forms.IntegerField()
    django_hacker = forms.Boolea         


        
13条回答
  •  囚心锁ツ
    2020-11-27 10:23

    Use django-widget-tweaks, it is easy to use and works pretty well.

    Otherwise this can be done using a custom template filter.

    Considering you render your form this way :

    {{ form.non_field_errors }}
    {{ form.subject.errors }} {{ form.subject }}

    form.subject is an instance of BoundField which has the as_widget method.

    you can create a custom filter "addcss" in "my_app/templatetags/myfilters.py"

    from django import template
    
    register = template.Library()
    
    @register.filter(name='addcss')
    def addcss(value, arg):
        css_classes = value.field.widget.attrs.get('class', '').split(' ')
        if css_classes and arg not in css_classes:
            css_classes = '%s %s' % (css_classes, arg)
        return value.as_widget(attrs={'class': css_classes})
    

    And then apply your filter:

    {% load myfilters %}
    
    {{ form.non_field_errors }}
    {{ form.subject.errors }} {{ form.subject|addcss:'MyClass' }}

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

    Hope this help.

    EDIT 1

    • Update filter according to dimyG's answer

    • Add django-widget-tweak link

    EDIT 2

    • Update filter according to Bhyd's comment

提交回复
热议问题