Search code examples
pythondjangodjango-filter

How do you set a default value for django-filter select field instead of a blank field?


I'm using the django-filterapp to filter items on my front end and i can't seem to understand how to populate the first value on my dropdown select field with a default value instead of the blank -------- space on the field, its really bad for user experience since im not using labels and therefore users wont be able to identify a field without a placeholder of some sort. Here is what i'm getting.

enter image description here


Solution

  • By creating a class for the filter and inherit from filter set and use the empty_label propriety like below example:

    filter class:

    class StudentFilter(django_filters.FilterSet):
    
        student__nationality = ModelChoiceFilter(queryset=Nationality.objects.all(), empty_label=('Nationality'))
    
        class Meta:
            model = Student
            fields = {
                'student__nationality': ['exact'],
            }
    
    

    In view only use this command:

    model = Student
    filterset_class = StudentFilter
    

    for more information, check (https://django-filter.readthedocs.io/en/master/ref/filterset.html)