passing django variables as parameters into href url


On my home page i want to have 3 links that will redirect the user to a page ('<str:name>') which will display the name that they clicked. I would like to use a for loop to create links for these names as i plan to have much more than 3 names.

I have tested with the two methods (for loop / manually writing out all of the links) but can’t get the for loop to work.

I thought these two methods below would produce the same result.

    <h2>does not work</h2>
    {% for person in people %}
        <a href="{% url 'person' '{{person}}'  %}">{{person}}</a>
    {% endfor %}

    <a href="{% url 'person' 'logan' %}">logan</a>
    <a href="{% url 'person' 'paul' %}">paul</a>
    <a href="{% url 'person' 'nicola' %}">nicola</a>

What the urls look like in page source:

enter image description here

def home(request):
    return render(request, "APP/home.html", context={"people":['logan', 'paul', 'nicola']})

def person(request, name):
    return render(request, 'APP/person.html', context={"name":name})

urlpatterns = [
    path('home/', views.home, name='home'),
    path('person/<str:name>/', views.person, name='person'),
Asked By: logan_9997



You don’t need to wrap person variable into {{}} signs since in url tag you should use it directly:

{% for person in people %}
    <a href="{% url 'person' person  %}">{{person}}</a>
{% endfor %}

Check example here.

Answered By: neverwalkaloner