Search code examples
djangodjango-tables2django-filters

Add label or modifying widget on django-filter form


I'm looking for a way of specifying what the select fields in the filter form are for, this is how it looks like right now:

enter image description here

And is hard to understand what the select inputs are for, the ideal would be to change the default option ("Unkown" and "--------") but it should be custom for each one. Already tried that but couldn't find a way to do it, it is possible? If someone knows a way of doing this it would be great.

Adding a label should be the easier way, but don't know how to do it.

filters.py

class PatientFilter(django_filters.FilterSet):
    class Meta:
        model = Patient
        fields = {
            'dni': ['exact'],
            'first_name': ['icontains'],
            'last_name': ['icontains'],
            'risk': ['exact'],
            'status': ['exact'],
            'ubication': ['exact'],
            'supervisor': ['exact'],
        }

HTML

    {% if filter %}
        <form action="" method="get" class="form form-inline">
            {% bootstrap_form filter.form layout='inline' field_class="mr-3 mt-3" %}
            <div class="mt-3">
            {% bootstrap_button 'Filter' button_class="btn-secondary" %}
            <a href="{% url 'patients' %}" class="ml-3 btn btn-secondary">Clear</a>
            </div>
        </form>
    {% endif %}

The select inputs are foreign keys, here is its definition in models.py

status = models.CharField(max_length=15, choices=STATUS_CHOICES)
ubication = models.ForeignKey(Ubication, on_delete=models.CASCADE)
supervisor = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)

I'm using tables2 with django-filters.


Solution

  • you can do this by adding empty_label to your ModelChoiceFilters.

    class PatientFilter(django_filters.FilterSet):
    
        ubication = django_filters.ModelChoiceFilter(
            queryset=Ubication.object.all(),
            empty_label="Placeholder",
        )
    
        class Meta:
            model = Patient
            fields = {
                'dni': ['exact'],
                'first_name': ['icontains'],
                'last_name': ['icontains'],
                'risk': ['exact'],
                'status': ['exact'],
                'ubication': ['exact'],
                'supervisor': ['exact'],
            }  
    

    Edit:
    For adding placeholder to CharFields you can try this:

    from django.forms.widgets import TextInput  
    
    
    class FooFilter(filters.FilterSet):
         bar = filters.CharFilter(..., widget=TextInput(attrs={'placeholder': 'baz'}))