Opened 51 minutes ago
#37562 new Bug
Admin changelist search crashes (500) on "NaN" and out-of-range datetime terms for `__exact` search_fields
| Reported by: | Kingsley | Owned by: | |
|---|---|---|---|
| Component: | contrib.admin | Version: | 6.1 |
| Severity: | Normal | Keywords: | search_fields exact |
| Cc: | Triage Stage: | Unreviewed | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
Since #36865 (4cecf3039586ea738afafb9a28c946bff42c37c1, new in Django 6.1), ModelAdmin.get_search_results() validates each search term for a non-text <field>__exact entry in search_fields with formfield().to_python(), then passes the converted value to the ORM. #37263 fixed this for fields with choices and for BooleanField. Some values still pass to_python() but are rejected later by the model field or by the database backend. The changelist then returns a 500:
DecimalField:forms.DecimalField.to_python()acceptsNaN,Infinity,-infandsNaN(onlyforms.DecimalField.validate()rejects non-finite values).models.DecimalField.get_prep_value()then raisesValidationErrorinsidequeryset.filter(). This happens before any SQL runs, so it doesn't depend on the database backend. Each term is OR'd across allsearch_fields, soq=nancrashes even when a row'sCharFieldcontains "nan". A multi-word search such aswidget nancrashes too.DateTimeFieldwithUSE_TZ = True: a term that overflows when the backend converts it to UTC raisesOverflowError: date value out of rangefromtimezone.make_naive()inadapt_datetimefield_value(), when the query is compiled. Examples:q=0001-01-01with a current time zone ahead of UTC (e.g. Europe/Paris), andq=9999-12-31T23:59with one behind UTC (e.g. America/New_York). I reproduced this on SQLite only. Backends that keep aware datetimes, such as PostgreSQL, may not be affected.DateTimeFieldwithUSE_TZ = False: a term with a UTC offset, e.g.q=2020-01-01T00:00+05:00, raisesValueError: SQLite backend does not support timezone-aware datetimes when USE_TZ is False.(SQLite only tested.)
The docs say that for non-text fields with an explicit lookup, "search terms that are invalid for that field type are skipped".
To reproduce:
# models.py class Item(models.Model): title = models.CharField(max_length=40) cost = models.DecimalField(max_digits=10, decimal_places=2) # admin.py @admin.register(Item) class ItemAdmin(admin.ModelAdmin): search_fields = ["title", "cost__exact"]
Log in as any staff user with the view permission for Item and open /admin/<app>/item/?q=NaN:
File "django/contrib/admin/options.py", line 1408, in get_search_results
queryset = queryset.filter(models.Q.create(term_queries))
...
File "django/db/models/lookups.py", line 94, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "django/db/models/fields/__init__.py", line 1924, in get_prep_value
return self.to_python(value)
File "django/db/models/fields/__init__.py", line 1909, in to_python
raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ['βNaNβ value must be a decimal number.']
Results (SQLite, all three cases):
- 5.2.20, 6.0.11: 200
- b25bc24418 (parent of 4cecf30): 200
- 4cecf3039586: 500
- 6.1, 6.1.3, 6.1.4, main (5b0c26e7f6): 500
#37263 fixed the same regression for other field types, but its thread and PR don't mention decimals or datetimes. In the review of βPR 21754, the stated aim was to "exclude term values that will crash the query". #34191 (closed as a duplicate of #26001) was an older crash for terms that can't be parsed as a decimal at all.
I have a patch that also prepares each converted term for the database, with the same calls the exact lookup makes (field.get_db_prep_value(field.get_prep_value(value), connection, prepared=True), non-relational fields only). It skips the lookup when that raises ValidationError, ValueError or OverflowError. A narrower alternative that fixes only case 1 is to also call formfield.validate(value) for forms.DecimalField. validate() only checks required-ness and finiteness, not validators such as max_digits, so it doesn't reject terms that clean() would.
Related, but not fixed by that patch: a DurationField __exact entry with q=P999999999D also gives a 500 on SQLite since 6.1. The error is OverflowError: Python int too large to convert to SQLite INTEGER, raised by the sqlite3 driver at execution. Django prepares that value without error, so preparing the term can't detect it. I'm happy to handle it here or in a separate ticket.
This issue was found with the help of an AI assistant (Claude). I reviewed the analysis and re-ran the reproduction myself before filing.