Define css class in django Forms

前端 未结 13 824
南旧
南旧 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:22

    In case that you want to add a class to a form's field in a template (not in view.py or form.py) for example in cases that you want to modify 3rd party apps without overriding their views, then a template filter as described in Charlesthk answer is very convenient. But in this answer the template filter overrides any existing classes that the field might has.

    I tried to add this as an edit but it was suggested to be written as a new answer.

    So, here is a template tag that respects the existing classes of the field:

    from django import template
    
    register = template.Library()
    
    
    @register.filter(name='addclass')
    def addclass(field, given_class):
        existing_classes = field.field.widget.attrs.get('class', None)
        if existing_classes:
            if existing_classes.find(given_class) == -1:
                # if the given class doesn't exist in the existing classes
                classes = existing_classes + ' ' + given_class
            else:
                classes = existing_classes
        else:
            classes = given_class
        return field.as_widget(attrs={"class": classes})
    

提交回复
热议问题