On my home page i want to have 3 links that will redirect the user to a page ('127.0.0.1:8000/person/<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 %}
<h2>works</h2>
<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:
views.py
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})
urls.py
urlpatterns = [
path('home/', views.home, name='home'),
path('person/<str:name>/', views.person, name='person'),
]
CodePudding user response:
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.