DCR
DCR

Reputation: 15665

adding multiple values in django path

I have the following paths set up:

urlpatterns = [
path("", views.index, name="index"),
path('entry/<str:title>', views.entry, name='entry'),
]

my entry method is:

def entry(request,title):
entries = []
entry = util.get_entry(title)    
if entry != None:
    entries.append(entry)

return render(request, "encyclopedia/entry.html", {
    "title": title,
    "entries": entries,
})

and in my html we have:

{% block body %}
    <h1>All Pages</h1>
    <ul>
    {% for entry in entries %}
        <li>
     a href = "{% url 'entry' title=entry  %}" >{{ entry }}</a>
        </li>
    {% endfor %}
   </ul>
{% endblock %}

two questions:

  1. Is this the right way to pass parameters with a link?
  2. What would I need to change to pass multiple parameters?

Upvotes: 1

Views: 932

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

Is this the right way to pass parameters with a link?

Yes, by using the {% url … %} template tag [Django-doc] you calculate the path for a given view name and parameter(s).

There is however a small error in the HTML: you need to open the <a> tag, and furthermore not use spaces between the equal sign (=):

<a href="{% url 'entry' title=entry %}">{{ entry }}</a>

What would I need to change to pass multiple parameters?

You define extra parameters in the view, for example:

urlpatterns = [
    # …,
    path('entry/<str:title>/<str:theme>/', views.entry, name='entry'),
]

and you specify values for the two parameters:

<a href="{% url 'entry' title=entry theme='mytheme' %}">{{ entry }}</a>

the view then takes three parameters:

def entry(request, title, theme):
    # …

Upvotes: 2

Related Questions