New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Default filtering when no filter parameters passed in request.GET #322
Comments
Hi @andrius-senulis. django-filter is built on top of regular django forms, so this question can be boiled down into "How do I provide default field values for bound forms?" Per this SO answer, you can add a class DecimalDefaultField(forms.DecimalField):
def clean(self, value):
if value is None:
return 4.0
return super(DecimalDefaultField, self).clean(value)
class NumberDefaultFilter(filters.NumberFilter):
field_class = DecimalDefaultField
class MyFilterSet(FilterSet):
some_field = NumberDefaultFilter(name='some_field')
... An easier method would be to just inspect the incoming data and set a default value. def your_view(request):
data = request.GET.copy()
data.setdefault('some_field', 'some_value')
f = YourFilterSet(data, queryset=YourModel.objects.all())
... edit: class MyForm(forms.Form):
clean_some_field(self, value):
...
class MyFilterSet(FilterSet):
class Meta:
model = MyModel
form = MyForm
fields = ['some_field'] |
I use a FilterView. Overriding get_filterset_kwargs works for me: class MyFilterView(FilterView):
filterset_class = filters.MyFilter
# ...
def get_filterset_kwargs(self, filterset_class):
kwargs = super(MyFilterView, self).get_filterset_kwargs(filterset_class)
if kwargs["data"] is None:
kwargs["data"] = {"is_very_interesting": False}
return kwargs Edit: When using e.g. pagination, this is not applied (b/c data is not None). Something like this might work: if kwargs["data"] is None:
kwargs["data"] = {"is_very_interesting": False}
elif "is_very_interesting" not in kwargs["data"]:
kwargs["data"] = kwargs["data"].copy()
kwargs["data"]["is_very_interesting"] = False |
Using
|
the method with |
Providing default form/filter values in general is not recommended in that it's a bad practice that can have confusing/adverse effects. Implementing via |
You made my day! |
Dear all,
Is there an option to set the default filter field and value to use if no parameter that I define in the Meta.fields has been found in the request object?
If there isn't such an option, what would you suggest as the best way to do it?
Regards,
Andrius
The text was updated successfully, but these errors were encountered: