0

I am using django_filter package for custom filtering in my django rest framework API, Below is the given code

import django_filters
from src.core.models.rough_management import DocumentDetails


class DocumentDetailsFilter(django_filters.FilterSet):

    my_date = django_filters.DateFromToRangeFilter()

    class Meta:
        model = DocumentDetails
        fields = ['my_date']

Here i am getting "Enter a valid date" as an exception message when i enter invalid date range so my question is how to pass custom exception message to "No records found"?

1 Answer 1

1

Django filters use native django form fields to validate data. DateFromToRangeFilter use django.forms.fields.DateField. (Django DateField code)

You need to implement your own custom filter with little changes.

Not that from my perspective it's bad practice because that code interferes DateField error which should return default error as it is "Enter a valid date" and it's good information from api if you enter invalid date value like text "abcd".

Anyway for now i don't see better place to implement that and that is simpler than interference in FilterSet class.

You can also look on original code here to see how it's designed.

class CustomDateField(django.forms.fields.DateField):
    default_error_messages = {
        "invalid": "No records found",
    }

class CustomDateRangeField(RangeField):
    widget = DateRangeWidget

    def __init__(self, *args, **kwargs):
        fields = (CustomDateField(), CustomDateField()) # Important change here only
        super().__init__(fields, *args, **kwargs)

    def compress(self, data_list):
        # Compress method stay the same as it is in original code
        if data_list:
            start_date, stop_date = data_list
            if start_date:
                start_date = handle_timezone(
                    datetime.combine(start_date, time.min), False
                )
            if stop_date:
                stop_date = handle_timezone(
                    datetime.combine(stop_date, time.max), False
                )
            return slice(start_date, stop_date)
        return None


class CustomDateFromToRangeFilter(RangeFilter):
    field_class = CustomDateRangeField
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.