karlosss
karlosss

Reputation: 3155

Django-filter for nullable Boolean Field

I would like to use django-filter for BooleanField(blank=True, null=True). When I use it out of the box, the form generates three options: Unknown (no filtering), Yes (True) and No (False). However, I need a fourth option for None so that the filter specifically selects those records with value None.

My model (relevant part):

class Record(Model):
    accepted = BooleanField(blank=True, null=True, verbose_name=_("Accepted?"))

My filter (relevant part):

class RecordFilter(FilterSet):
    class Meta:
        model = Record
        fields = OrderedDict((
            ("accepted", ["exact"]),
        ))

My view:

class RecordList(LoginRequiredMixin, FilterView):
    model = Record
    paginate_by = 25
    template_name = "record/record_list.html"
    filterset_class = RecordFilter

My template (relevant part):

<form method="get" role="form" class="form">
      {{ filter.form.as_p }}
      <button>{% trans "Filter" %}</button>
</form>

How can I achieve the desired behavior?

Upvotes: 1

Views: 2834

Answers (1)

Sherpa
Sherpa

Reputation: 1998

This can be solved by constructing a ChoiceFilter with the correct arguments, as a user demonstrated here.

That said, the framework should fully support NullBooleanFields, and I've opened an issue to resolve this.

Upvotes: 1

Related Questions