带有断线和重定向 url 的 Django 消息

Django message with breakline and redirect url inside

我想用一些东西改进我的 django message:在文本中添加一个 breakline 并使用 django reverse url 添加一个 url。

这是我的留言:

messages.error(self.request, _(  f"The link to download the document has expired. Please request it again in our catalogue : {redirect to freepub-home}" 

我想通过在 . 之后添加一个新行来分隔我的消息,以获得类似这样的内容:

messages.error(self.request, _(  f"The link to download the document has expired. 
                                   Please request it again in our catalogue : {redirect to freepub-home}" 

然后,如何通过反向 url 到 "freepub-home" 在我的消息中设置 django 重定向?

提前致谢!

编辑:

我克服设置断线:

messages.error(self.request, mark_safe(
            "The link to download the document has expired." 
            "<br />"
            "Please request it again in our catalogue : 
            <a href='{% url "freepub-home" %}'> my link </a>")

但是到目前为止我还没有找到如何在内部传递 django url 因为我对引号和双引号有疑问。

您传递给 mark_safe 的是纯字符串,它不会被解释为 Django 模板,因此您不能在其中使用模板标记语法。您必须使用 reverse() 函数来获取 url 和 python 字符串格式语法来构建消息:

from django.core.urlresolvers import reverse

# ...

    # using triple-quoted string makes life easier
    msg = """
        The link to download the document has expired. 
        <br />
        Please request it again in our catalogue : 
        <a href='{url}'> my link </a>
        """
    url = reverse("freepub-home")
    messages.error(self.request, mark_safe(msg.format(url=url)))