【问题标题】:Is it possible to use template tags in ValidationError's strings?是否可以在 ValidationError 的字符串中使用模板标签?
【发布时间】:2011-02-21 21:24:20
【问题描述】:

我需要抛出包含锚点的 ValidationError。

if not profile.activated():
    raise ValidationError('Your profile is not activated. <a href="{% url resend_activation_key %}">Resend activation key</a>.')

我需要修改什么才能使它工作?

【问题讨论】:

    标签: python django validation django-templates django-forms


    【解决方案1】:

    为什么要在这里使用模板标签?模板标签用于模板中。如果要查找反向 URL,请使用 reverse 函数。

    【讨论】:

      【解决方案2】:

      首先:不要这样做!将 HTML 代码放在它所属的位置:放入模板中。

      第二:你也许可以用

      做到这一点
      from django.template import Context, Template
      t = Template(u"Your profile is not.... {% url blah %} ...")
      raise ValidationError( t.render(Context())
      

      但 html 标签会被转义,除非你在模板中将它们标记为安全。

      【讨论】:

      • 第一个音符是声音。但是我该怎么做呢?也许通过设置特殊的表单属性?
      • 难道你不能在显示表格之前检查个人资料激活吗?在你看来类似的东西:如果 request.method == "GET" 而不是 profile.activated(): redirect_to_url_describing_problem
      猜你喜欢
      • 2017-05-27
      • 2022-01-04
      • 2019-06-22
      • 2015-01-02
      • 2019-09-16
      • 1970-01-01
      • 2019-02-22
      • 2012-06-20
      相关资源
      最近更新 更多