Skip to content

Instantly share code, notes, and snippets.

@dpetzel dpetzel/
Last active Nov 28, 2019

What would you like to do?


from django.forms.widgets import NullBooleanSelect
from django.db import models
from django import forms

from django_filters.filters import BooleanFilter
from django_filters.filterset import FilterSet

from rest_framework.filters import DjangoFilterBackend

class NullBooleanSelectFixed(NullBooleanSelect):
    def value_from_datadict(self, data, files, name):
        value = data.get(name, None)
        if value in (True, 'True', 'true', '1'):
            return True
        elif value in (False, 'False', 'false', '0'):
            return False
            return None

class NullBooleanFieldFixed(forms.NullBooleanField):
    widget = NullBooleanSelectFixed

class BooleanFilterFixed(BooleanFilter):
    field_class = NullBooleanFieldFixed

class SmarterFilterSet(FilterSet):
    filter_overrides = dict(FilterSet.filter_overrides,
        **{models.BooleanField: {'filter_class': BooleanFilterFixed}})

class SmarterDjangoFilterBackend(DjangoFilterBackend):
    An extension of the DjangoFilterBackend that properly handles boolean types!topic/django-filter/vbTttMhqH0I
    default_filter_set = SmarterFilterSet

        # 'rest_framework.filters.DjangoFilterBackend'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.