Arnold96
Arnold96

Reputation: 123

Django dynamic URL in template

How can I use template variable in dynamic url. I want something like this:

href="{% url '{{ questionnaire.url }}' %}"

The problem is that I get this error:

Reverse for '{{ questionnaire.url }}' not found. '{{ questionnaire.url }}' is not a valid view function or pattern name.

Update:

The problem is here in my javascript:

<script>
let el = `<a href="{% url '${questionnaire.url}' %}"></a>
</script>

I insert this code in my template dynamic, and the Django template cant resolve the url correctly.

Upvotes: 2

Views: 2206

Answers (2)

shafikshaon
shafikshaon

Reputation: 6404

You can use with template tag

{% with my_url=questionnaire.url %}
   <a href="{% url my_url %}">Go</a>
{% endwith %}

Upvotes: 0

funnydman
funnydman

Reputation: 11376

Take a look at url documentation. You can pass a view name and Django will resolve it:

view.py

path('some-url/', app_views.client, name='app-views-client')

index.html

<a href="{% url 'app-views-client' %}" >Go</a>

Upvotes: 2

Related Questions