仅将字符串的一部分标记为安全

时间:2018-03-29 19:36:29

标签: django django-templates django-template-filters

我想在评论中显示用户的个人资料链接,即u / ali应该看起来像是指向用户个人资料的链接。但我也不想冒险将整个评论标记为安全,因为它会使网站容易受到html注入,所以我的问题是:如何标记安全只是字符串的一部分,而不是将整个注释标记为保存? 这是templatetags代码:

@register.filter(name='mentioned_profiles')
def mentioned_profiles(comment):
    words = comment.split(" ")

    for word in words:
        if word[:2]=="u/":
            u = word[2:]
            try:
                user = User.objects.get(username=u)
                new_word = """<a href="http://127.0.0.1:8000/u/{}"> {}</a>""".format(user.username,user.username)
                new_word = mark_safe(new_word)
                comment = comment.replace(word,new_word)
            except:
                pass
    return comment

目前,它显示整个字符串,但未显示链接。

0 个答案:

没有答案