Search code examples
djangourltagsescapingquotes

Django. Use url tags inside quotes, inside quotes


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.


Solution

  • {% url ... %} is a template mechanism. Do not try to use it from outside a template. Rather, do yourself in the view what it would do:

    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)
    

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

    For comparison, here are two other ways how links can be generated (unrelated to your question):

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

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