Search code examples
djangodjango-viewsdjango-templateshrefdjango-urls

Django href pass multiple parameters to function


I want to pass two parameters from an HTML page throw href to a function first the parameter are: HTML page,

{{object.id}}
.
.
 {% for item in model_items %}
<td>{{item.ID}}</td>
<td class="p-1 mb-1 text-dark">
<a href="{% url 'Up_Items' item.id {{object.id}} %}" class="btn btn-info btn-sm">Add Item</a></td>

and the second thing is the urls.py;

 path('Up_Items/<int:id_itm,id_itm2>/', views.ADD_item, name='Up_Items'),

and the function in views.py.

def ADD_item(request, id_itm, id_itm2):
    print(id_itm, id_itm2 )
    return redirect('Invoices')

what I missed here to work correctly plseae?


Solution

  • You can define a path with two (or more) parameters with:

    path('Up_Items/<int:id_itm>/<int:id_itm2>/', views.ADD_item, name='Up_Items'),

    we thus define two variables id_itm and id_itm2, and both have <int:…> as path converter. We use a slash between the two to make it clear where one id stops and the other starts. You can also work with a comma for example, but a slash is more common and a comma should require percent-encoding [wiki].

    then we can define a function with:

    def ADD_item(request, id_itm, id_itm2):
        # …
        pass

    and refer to it with:

    <a href="{% url 'Up_Items' item.id object.id %}">