I'm developing a REST API with django rest framework but I'm not finding a way of validating the inputs from the request with django-filters.
For example, say I have the model:
class Event(models.Model):
timestamp = models.DateTimeField(help_text="Time it was created")
is_important = models.BooleanField(help_text="If the event is important")
And I have the filter:
class EventFilter(filters.FilterSet):
important = filters.BooleanFilter(name='is_important')
since = filters.IsoDateTimeFilter(name='timestamp', lookup_type='gt')
class Meta:
model = Event
If, in my request, I insert a bad date like {url}/?since=2016-02-31T00:00Z or {url}/?since=yesterday, instead of receiving feedback about what is wrong with the request, the API will just returns a list without any results. This doesn't indicate that the developer made a bad request, it could just mean that there are no events under those terms.
The inverse happens with booleans, if in my request I send {url}/?is_important=maybe, it will return all the results without any filtering.
So, my question is: Does DRF have a way of validating these kind of inputs and return a meaningful response to the developer? Thank you.
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