Django. Use url tags inside quotes, inside quotes

2019-04-02 07:44发布

问题:

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.