Opened 4 years ago

Closed 4 years ago

#31203 closed Bug (wontfix)

Using Markup in ValidationError.

Reported by: Felipe Owned by: nobody
Component: Core (Other) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Felipe)

Not 100% positive this is a bug, but definitely a breaking change in Django.

In 1.11 ValidationError used force_text to stringify its messages, but in 2.2 and 3.0, it's using str.

force_text used to check for subtypes of six.text_type and let those through unchanged, whereas str forces the __str__ conversion.

This interacts poorly with Markup, which 'unwraps' itself in the __str__ method. Here's a sample problem:

type(next(iter(ValidationError(
    message=Markup('%(x)s had a problem'),
    params={'x': Markup('<span>X</span>')}
)))) is str

That error should render on a form as a span followed by some text; however, the use of str causes the 'safeness' of the markup to be lost and thus it's re-escaped and the HTML leaks into the page.

Maybe Markup should be returning self in __str__, since it's a __str__ subclass. This bug can be worked around from client code using something like this:

class StubbornMarkup(Markup):
    def __str__(self):
        return self


type(next(iter(ValidationError(
    message=StubbornMarkup('%(x)s had a problem'),
    params={'x': Markup('<span>X</span>')}
)))) is StubbornMarkup

This is vaguely related to #13723, which seems to suggest the use of Markup should be supported.

Change History (2)

comment:1 by Felipe, 4 years ago

Description: modified (diff)

comment:2 by Mariusz Felisiak, 4 years ago

Component: Error reportingCore (Other)
Owner: set to nobody
Resolution: wontfix
Status: newclosed
Summary: Using Markup in ValidationErrorUsing Markup in ValidationError.

Thanks for this ticket, however ValidationError didn't respect SafeString when params was used even in Django < 2.0 (see #24639). Without params it preserves safeness of django.utils.safestring.SafeString in Django 1.11+, e.g.

ValidationError(message=SafeString('<span>sth</span> had a problem'))
Note: See TracTickets for help on using tickets.
Back to Top