Search code examples
pythondjangodjango-filter

Adding placeholder to form in Django when using django-filter


I am developing a web application which displays an html table using django-tables2 and which allows filtering this table using django-filter. In my html template I can simply put {% filter.form %} and I am getting a full form for filtering my table which I think is really great and easy.

However, I would like to add placeholders to this form which would be in plane html (using Bootstrap4) something like this:

<div class="container">
    <form>
        <div class="form-group">
            <label for="email">Email:</label>
            <input type="email" class="form-control" id="email"
             placeholder="ENTER PLACEHOLDER HERE" name="email">
            </div>
       </form>
    </div>

(example taken form here:https://www.w3schools.com/bootstrap4/tryit.asp?filename=trybs_form_basic&stacked=h and edited)

How can I add a placeholder when working with django-filters and all I am doing is adding % filter.form %} to my template?

Edit: My question was half complete. The answer given by @schwobaseggl works great for most filters. However, when having a RangeFilter and two fields show up (one for the max value and one for the min value) how to set two separate placeholders? One can put the same placeholder into both fields as explained here: How to put placeholder in Django date range filter.


Solution

  • When you define your Filter, provide the placeholder attribute via the attrs kwarg of the widget constructor:

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