Search code examples
djangodjango-modelsdjango-formsdjango-templatesdjango-filters

how can i add Django Filter in one line by removing the label and making it placeholder?


this is my filters.py

class StudentFilterSel(django_filters.FilterSet):
class Meta:
    model=Student
    fields=['registrationSession','registrationNumber','studentName','applyingForClass','studentDob','studentAadharNum','fathersName','fathersContactNumber']

this is my views.py

def selectedList(request):
Studentss=Student.objects.filter(AdmissionStatus='Selected')
myFilter=StudentFilterSel(request.GET,queryset=Studentss)
Studentss=myFilter.qs
return render(request,"register/selectedList.html",{'myfilter':myFilter,"Studentss":Studentss})

this is my HTML file

<form method='get'>
{{myfilter.form}}
<button type="submit">search</button>
 </form>

I need a lot of filters in my table but they are getting distorted and getting in multiple lines how can I remove the label and change it to the placeholder to reduce space?


Solution

  • You can customise the widget, like you would in a form. The following would work on a text input field:

    studentName = django_filters.CharFilter(label='', 
                     lookup_expr='icontains', 
                     widget=forms.widgets.TextInput(attrs={'placeholder':'Student Name'}))
    

    Or you could do it in the the filter's init. The following would work for a choice field:

    def __init__(self, *args, **kwargs):
        super(StudentFilterSel, self).__init__(*args, **kwargs)
        self.filters['registrationSession'].label = ''
        self.filters['registrationSession'].extra['empty_label'] = "Registration"