1

I want have my url come from views.py and then I can pass it as variable to href tag in template.

views.py:

context {
    'urlLink': "{% url 'myapp:theURL' %}"
    ...
}

index.html:

<a href="{{ urlLink }}" LINK 1 </a>

I have the above and it is not working. I have also tried <a href="{{ urlLink|escape }}" LINK 1 </a> but no success.

2 Answers 2

2

If you need to use something similar to the {% url %} template tag in your view code, Django provides the django.core.urlresolvers.reverse(). The reverse function has the following signature:

reverse(viewname, urlconf=None, args=None, kwargs=None)

So in your context:

context {
    'urlLink': reverse('viewname')
}

Then you can use in your template:

<a href="{{urlLink}}">Link1</a>
Sign up to request clarification or add additional context in comments.

Comments

1

you need reverse

context {
    'urlLink': "%s" % reverse('view_name')
}

you cannot use {% url 'myapp:theURL' %} in views.py since this is a template tag

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.