Django. Use url tags inside quotes, inside quotes

筅森魡賤 提交于 2020-01-12 10:38:31

问题


I want to pass this variable to the context and render it, it includes html tags.

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

As you can see, I have tried escaping the quotes inside the href=" ". But I get this error:

%u format: a number is required, not unicode

So, I guess the error happens when "% url .." %() is evaluated. I have tried many things without success.

Extra information:

The url "pefiles:perfil" recieves two arguments:

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

the arguments are a username and a queryset, the first one comes from notificacion.actor.usuario.username and the second one is a string, 'recientes'.

Thanks in advance for your help.


回答1:


Generate URL in view

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)

Check Django URLresolvers

Generate URL in template (HTML)

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

Generate URL in jQuery

<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>

The official Django documentation is quite well-explained so I recommend you to check Django URLresolvers




回答2:


There's no need to escape any of those quotes. The context for evaluating the code inside the template tag is completely separate from the surrounding HTML, so they do not interfere.



来源:https://stackoverflow.com/questions/23842090/django-use-url-tags-inside-quotes-inside-quotes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!