[Fixed]-DRF – Giving feedback to developer regarding bad inputs using django-filters

1👍

django-filter has a strict attribute which controls the handling of validation errors.

import django_filters as filters
from django_filters.filterset import STRICTNESS

class EventFilter(filters.FilterSet):
    important = filters.BooleanFilter(name='is_important')
    since = filters.IsoDateTimeFilter(name='timestamp', lookup_type='gt')

    strict = STRICTNESS.RAISE_VALIDATION_ERROR

    class Meta:
        model = Event
👤Sherpa

0👍

from django_filters.filterset import STRICTNESS

Above import will results to ImportError: cannot import name ‘STRICTNESS’

This is because STRICTNESS was moved: https://django-filter.readthedocs.io/en/latest/guide/migration.html#filterset-strictness-handling-moved-to-view-788

There is no official documentation yet but I was able to trigger/raise the error by override of FilterBackend from the comment
https://github.com/carltongibson/django-filter/pull/788#issuecomment-409635087

class StrictDjangoFilterBackend(django_filters.rest_framework.DjangoFilterBackend):
    """Return no results if the query doesn't validate."""

    def filter_queryset(self, request, queryset, view):
        try:
            return super().filter_queryset(request, queryset, view):
        except serializers.ValidationError:
            return queryset.none()

sample working api call on my datetimefield (time has to be present):

GET /api/xxxx?start_date=2015-01-01T0:0:00Z
👤newbee

Leave a comment