ModelMultipleChoiceFilter does not validate GET request parameter?: ValueError if not int
tombreit opened this issue · comments
Problem
I have a working django-filter based ModelMultipleChoiceFilter
implementation (see below).
A valid (and functional) request could be:
http://fqdn/?authors_filter=9684
But if I get a "malformed" request, say:
http://fqdn/?authors_filter=9xyz4
I get a ValueError
: Field 'id' expected a number but got '9dyz4'.
, resulting in a ServerError with DEBUG = False
.
Questions
- Where am I missing some kind of validation/sanitizing for these kind of URL GET parameters?
- How can this filter validate the type (here: integer) before trying to build a queryset filter?
Guesswork
Perhaps the ModelMultipleChoiceFilter
does not handle this validation, but another filter (eg. NumberFilter
) must be used in conjunction with ModelMultipleChoiceFilter
(mentioned in #824 (comment))? But I did not manage to mix these two filters successfully...
Implementation
# models.py
class Author(models.Model):
last_name = models.CharField(max_length=255)
first_name = models.CharField(max_length=255, blank=True)
# filters.py
class PublicationFilter(django_filters.FilterSet):
authors_filter = django_filters.ModelMultipleChoiceFilter(
field_name='authors__id',
to_field_name='id',
queryset=Author.public_objects.all(),
)
class Meta:
model = Publication
strict = False
fields = (
'authors_filter',
)
Versions
Django 4.0.3
django-filter 21.1
SO
Already tried via https://stackoverflow.com/q/70659936/5071435 ....
Sorry for the noise: the 500 for malformed request parameters (e.g. ?authors_filter=70--XYZ--56&
instead of ?authors_filter=7056&
was caused by the wrong widget I used (django_select2.forms.ModelSelect2MultipleWidget
instead of django_select2.forms.Select2MultipleWidget
).