Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django : url tag -> how to use a variable as url_name?

Tags:

django

I have a django view which declare a target variable :

target  = "name_of_next_view_to_call"
return render(request, template, locals() )

I want to use this target variable into my template, I tried the following :

<form action="{% url '{{target}}' %}" method="post">

which gives me an error :

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

How to use the value of my "target" variable as the name of the url to be constructed ? From the doc I know it should be possible :

The first argument is a URL pattern name. It can be a quoted literal or any other context variable.

like image 744
Romain Jouin Avatar asked Nov 05 '25 00:11

Romain Jouin


1 Answers

Within template tags, you don't need to mark context variables. They are usually recognized without the braces:

<form action="{% url target %}" method="post">

should work just fine. Just as you have probably used other tags in a similar way:

{% if target %}
# or
{% for obj in object_list %}

While some these examples are listed in the docs for template variables and tags, the point is not explicitly made there.

like image 59
user2390182 Avatar answered Nov 06 '25 13:11

user2390182



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!