I'm using django_filters. For boolean fields, it generates this HTML:
<select name="bass" id="id_bass">
<option value="">Unknown</option>
<option value="true" selected="">Yes</option>
<option value="false">No</option>
</select>
This springs from Django's own specifics of NullFields. How can I change that ugly 'Unknown' to something else? the user is not really searching for 'Unknown'; they're searching for 'all', since my boolean field is required and either true
or false
.
The widget does not accept a choices
attribute.
Creating manually the HTML myself partially solved the issue; nevertheless, I would achieve this from the view
and use only the {{form}}
on the template.
PS
The best way of doing it on the template is by simply running this JavaScript after the DOM has loaded:
document.getElementById('id_bass').options[0].innerText = "---------";
A bit hacky; still, it does what I want.
You can create a custom widget for that and can use it in your BooleanFilter()
as,
from django_filters.widgets import BooleanWidget
from django.utils.translation import gettext as _
class CustomBooleanWidget(BooleanWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.choices = (("", _("Anything else")), ("true", _("Yes")), ("false", _("No")))
class YourFilterSet(filters.FilterSet):
your_field = filters.BooleanFilter(widget=CustomBooleanWidget)
class Meta:
model = YourModelClass
fields = ("your_field",)