Skip to content

3.15.0 - bug in rendering % characters from ValidationError #9295

@smallwat3r

Description

@smallwat3r

The new 3.15.0 release introduced a bug in rendering errors from the ValidationError exception class.

Given a serializer:

class MySerializer(Serializer):
    departure_datetime = serializers.DateTimeField(
        required=True,
        format="%Y-%m-%d %H:%M:%S",
        error_messages={"invalid": "Expects format %Y-%m-%d %H:%M:%S"},
    )

Calling ValidationError would raise the exception:

  File "/.../.venv/lib/python3.11/site-packages/rest_framework/fields.py", line 603, in fail
    raise ValidationError(message_string, code=key)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/.../.venv/lib/python3.11/site-packages/rest_framework/exceptions.py", line 160, in __init__
    detail = [detail % params]
              ~~~~~~~^~~~~~~~
ValueError: unsupported format character 'Y' (0x59) at index 27

As expected, this can easily be reproduced in the console:

>>> ValidationError("Expects format %Y-%m-%d %H:%M:%S")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/.../.venv/lib/python3.11/site-packages/rest_framework/exceptions.py", line 160, in __init__
    detail = [detail % params]
              ~~~~~~~^~~~~~~~
ValueError: unsupported format character 'Y' (0x59) at index 16

or

>>> ["Expects format %Y-%m-%d %H:%M:%S" % {}]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: unsupported format character 'Y' (0x59) at index 16

A solution would be to escape with double % characters any occurrence of % in the error messages.

class MySerializer(Serializer):
    departure_datetime = serializers.DateTimeField(
        required=True,
        format="%Y-%m-%d %H:%M:%S",
        error_messages={"invalid": "Expects format %%Y-%%m-%%d %%H:%%M:%%S"},
    )

Unsure this is a choice by design or not, as this wouldn't be the case on 3.14.x?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy