JM Lontoc
JM Lontoc

Reputation: 221

django - using urls in templates from variable in views

Suppose I have this view

def foo_bar(request):

    context = {
        'url': 'app_name:foo"
    }

    return render(request, 'template.html', context)

And in the template, I want something like this:

<form action="{% url {{ url }} %}">
...
</form>

However, it throws ID expected

Is there a way to make this work?

Upvotes: 0

Views: 57

Answers (1)

Olzhas Arystanov
Olzhas Arystanov

Reputation: 986

Maybe a better way will be to use django reverse?

from django.urls import reverse

def foo_bar(request):

    context = {
        'url': reverse('app_name:foo'),
    }

    return render(request, 'template.html', context)

And in the template simply:

<form action="{{ url }}">
...
</form>

Upvotes: 4

Related Questions