gpt4 book ai didi

Django 。在引号内使用 url 标签,在引号内

转载 作者:行者123 更新时间:2023-12-02 04:30:02 25 4
gpt4 key购买 nike

我想将此变量传递给上下文并渲染它,它包含 html 标签。

notificacion_string = "<a href = \"{% url \'perfiles:perfil\' actor.usuario.username  \'recientes\' %}\" > %s </a> voted on your post" % (notificacion.actor.usuario.username)

如您所见,我尝试转义 href=""内的引号。但我收到此错误:

%u format: a number is required, not unicode

所以,我猜想在评估 "% url .."%() 时会发生错误。我尝试了很多事情但没有成功。

额外信息:

url“pefiles:perfil”接收两个参数:

 url(r'^(?P<username>\w+)/(?P<queryset>\w+)/$',views.perfil, name='perfil'),

参数是用户名和查询集,第一个来自 notificacion.actor.usuario.username,第二个是字符串“recientes”。

预先感谢您的帮助。

最佳答案

{% url ... %} 是一种模板机制。不要尝试从模板外部使用它。相反,你自己应该考虑一下它会做什么:

在 View 中生成 URL

from django.core.urlresolvers import reverse

# Generate the URL using the Django urlresolver reverse
url = reverse('perfiles:perfil', kwargs={'username': actor.usuario.username, 'queryset': 'recientes' })

# Then concatenate the URL as other string argument
notificacion_string = "<a href ='%s'> %s </a> voted on your post" % (url, notificacion.actor.usuario.username)

Django 官方文档解释得非常清楚,所以我建议您查看 Django URLresolvers

为了进行比较,这里还有另外两种生成链接的方法(与您的问题无关):

在模板中生成 URL (HTML)

<a href = "{% url 'perfiles:perfil' actor.usuario.username  'recientes' %}" >{{notificacion.actor.usuario.username}}</a> voted on your post"

在模板中用 jQuery 生成 URL

<script>
// Generate an URL with a fake username
var url = "{% url 'perfiles:perfil' 'FakeUsername' 'recientes' %}"

// Let's supose we received an AJAX response with a variable username
username = response['username']

// Replace the string 'FakeUsername' for the real one
url = url.replace('FakeUsername', username)
</script>

关于 Django 。在引号内使用 url 标签,在引号内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23842090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com