Opened 8 minutes ago

#37541 new Bug

Admin search for a lone quote character matches all rows

Reported by: Vaibhav Pant Owned by:
Component: contrib.admin Version: dev
Severity: Normal Keywords: admin, search
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

unescape_string_literal() accepts a string consisting of a single quote character and returns an empty string instead of raising ValueError:

>>> from django.utils.text import unescape_string_literal
>>> unescape_string_literal('"')
''
>>> unescape_string_literal("'")
''

The check s[-1] != s[0] passes for a one-character string, so s[1:-1] is empty.

ModelAdmin.get_search_results() has the same blind spot in its guard (bit.startswith(('"', "'")) and bit[0] == bit[-1], added for #32649). A search term that is a single " or ' is therefore unescaped to '', and the empty string matches every row.

Steps to reproduce

  1. Use a ModelAdmin with search_fields = ["name"].
  2. Create rows named plain, other and has"quote.
  3. Search the changelist for ".

Expected: only has"quote is returned.
Actual: all three rows are returned.

Proposed fix
Require len(s) >= 2 in unescape_string_literal(), and add len(bit) >= 2 to the quote check in get_search_results(). Fixing only the helper is not enough: the admin would then raise an uncaught ValueError when searching for a lone quote. This also applies to the unbalanced input from #32649, for example Foo "Bar "Baz".

Possible fix

django/utils/text.py:

  • django/utils/text.py

    a b def unescape_string_literal(s):  
    474     if not s or s[0] not in "\"'" or s[-1] != s[0]:
     474    if len(s) < 2 or s[0] not in "\"'" or s[-1] != s[0]:

django/contrib/admin/options.py:

  • django/contrib/admin/options.py

    a b class ModelAdmin(BaseModelAdmin):  
    1360                 if bit.startswith(('"', "'")) and bit[0] == bit[-1]:
     1360                if len(bit) >= 2 and bit.startswith(('"', "'")) and bit[0] == bit[-1]:

With both changes, unescape_string_literal('"') raises ValueError and the admin search above returns only has"quote. I ran utils_tests.test_text, admin_changelist, admin_views and template_tests.syntax_tests with both changes applied (1550 tests, OK).

Related: #32649 (unbalanced quotes), #6933 (quoted-phrase search, [26a41350]). This is not a duplicate of #34831, which is about limiting the number of OR'd search terms in the same loop.

I can prepare a patch with tests once the ticket is accepted.

AI disclosure
I found and reproduced this with Claude (Anthropic).

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top