【问题标题】:Django message with breakline and redirect url inside带有断线和重定向 url 的 Django 消息
【发布时间】:2019-05-05 15:07:45
【问题描述】:

我想改进我的django message:在文本中添加breakline,并使用django reverse 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,因为我有引号和双引号的问题。

【问题讨论】:

    标签: django django-messages


    【解决方案1】:

    您传递给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)))
    

    【讨论】:

    • 非常感谢!这正是我想要的;)
    猜你喜欢
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 2012-08-12
    • 2017-07-06
    相关资源
    最近更新 更多