繁体   English   中英

我的Django / Python代码不在<a>HTML页面中</a>呈现HTML <a>标记</a>

[英]My Django/Python Code is Not Rendering HTML <a> Tag in HTML Page

我想要一些类似于Twitter提及的内容,这些内容被转换为链接,但它不起作用。 如果我们假设我们有message ='别忘了带上Python书,@ friend'

#function to convert @mentions to links
def mentions(message, username):
    this_user_handle = reverse('mysite:profile', args=[username])
    new_message = re.sub(r'(@\w+)', r"<a href= '#'>\g<0></a>", message)
    new_message.replace('#', this_user_handle)
    return new_message

mentions(message, 'yax')返回Do not forget to come with the Python book, <a href= '#'>@friend</a>' #未被替换, new_message仍然显示在HTML页面中:

<p class= 'Post'>
    {{ new_message|linebreaksbr}}
</p>

这显示了这个:

Do not forget to come with the Python book, <a href= '#'>@friend</a>'

代替:

别忘了带上 Python书, @ friend

我该如何解决这个问题? 先感谢您!

Replace返回一个新字符串。

new_message = new_message.replace("#", "...")

此外,Django会自动转义模板中的HTML,以禁用它使用安全过滤器。

内容正在自动转义,以防止脚本注入等内容。 使用|safe过滤器,你确定它不能包含任何令人讨厌的东西。

使用kwargs而不是args:

reverse('profile', kwargs={'user_name': username})

你应该用href ='“替换href ='',以避免混合你不想混合的东西(你需要在几个地方替换它)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM