pythonpython-3.xdjangodjango-filter

django-filter how to add attribute to html tag under form


I'm using Django-filter,I tried to add attributes by using widget and attrs:

filter.py:

class MyFilter(django_filters.FilterSet):
    messageText = django_filters.CharFilter(widget=(attrs={'style':'width: 20px', 'class':'form-select form-select-sm'}))

    class Meta:
        model = Mymodel
        fields = ['messageText ']

Then I got:

SyntaxError: invalid syntax at here 'attrs={'

Any friend can help ?


Solution

  • The widget for a CharFilter is a TextInput [Django-doc]:

    from django.forms import TextInput
    
    
    class MyFilter(django_filters.FilterSet):
        messageText = django_filters.CharFilter(
            widget=TextInput(
                attrs={'style': 'width: 20px', 'class': 'form-select form-select-sm'}
            )
        )
    
        class Meta:
            model = Mymodel
            fields = ['messageText']