如何自定义验证错误消息在烧瓶中

发布于 2025-02-08 16:23:37 字数 757 浏览 1 评论 0原文

我在a 看起来像这样的:

def is_some_condition_true(arg: str) -> bool:
    return arg == "example"

def validation_func(self, arg: str) -> None:
    if not is_some_condition_true(arg):
        raise ValidationError("The <strong>validation</strong> failed")

如您所见,我正在尝试在错误消息中插入HTML。 Unfortunately, the result looks like this:

enter image description here

How can I put html in the validation error message without it being escaped?

I have a custom validator in a Flask-WTF form that looks like this:

def is_some_condition_true(arg: str) -> bool:
    return arg == "example"

def validation_func(self, arg: str) -> None:
    if not is_some_condition_true(arg):
        raise ValidationError("The <strong>validation</strong> failed")

As you can see, I'm trying to insert html in the error message. Unfortunately, the result looks like this:

enter image description here

How can I put html in the validation error message without it being escaped?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

巡山小妖精 2025-02-15 16:23:37

我最终选择了第二个答案来自@patrick yoder ,因为我无法完全获得工作的| safe trick的技巧,而且这种方式感觉有些整洁。

这就是我的代码现在的样子:

from markupsafe import Markup

def is_some_condition_true(arg: str) -> bool:
    return arg == "example"

def validation_func(self, arg: str) -> None:
    if not is_some_condition_true(arg):
        error_msg = Markup("The <strong>validation</strong> failed")
        raise ValidationError(error_msg)

I ended up going with the second answer from the question kindly pointed out by @Patrick Yoder, as I couldn't quite get the |safe trick to work and it just feels a bit tidier this way.

This is how my code looks like now:

from markupsafe import Markup

def is_some_condition_true(arg: str) -> bool:
    return arg == "example"

def validation_func(self, arg: str) -> None:
    if not is_some_condition_true(arg):
        error_msg = Markup("The <strong>validation</strong> failed")
        raise ValidationError(error_msg)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文