Ronaldo Lanhellas
Ronaldo Lanhellas

Reputation: 3336

Calling a function from HTML to Python file

I have a index.html page with a list of "cards", where each card have a "Click to Select" link.

When user click in this link i'd like to call a function in python to select this item, see:

def selectItem(request, item):
    #so something with this item

so, in my html pagE:

<div class="card-action">
                            <a href="{{ selectItem(myitem) }}">Selecionar</a>
                        </div>

This don't work. What is the right way to do it ?

Upvotes: 1

Views: 933

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476567

You can not call a function like that. A browser requests data with an HTTP request, and the server answers with an (HTTP) response. Such requests have a URL, and Django can route the request - with the URL - to the right view that will calculate a response.

We thus need to construct a view that can then be called. Your call is already quite close:

# app/views.py

from django.http import HttpResponse

def select_item(request, item_id):
    # so something with this item_id
    # ...
    return HttpResponse()

Since most objects are not serializable (and usually you do not want that anyway, since it would expose a lot of (potentially sensitive) data to the user, we thus need to work with an id (an identifier that is for example stored in the database that corresponds to an object).

The response contains the data in the response. Frequently that is HTML code that is then rendered by the browser.

Now in urls.py, we can specify how the url looks like, for example:

# app/urls.py

from django.urls import path
from app.views import select_item

urlpatterns = [
    path('select_item/<int:item_id>/', select_item, name='select_item_view'),
    # ...
]

The urlpatterns need to be included in the root urlpatterns (in the project root).

Now in the HTML template, we can generate the URL that matches with this view, something similar to:

<div class="card-action">
  <a href="{% url 'select_item_view' item_id=myitem.id %}">Selecionar</a>
</div>

Django will then make sure that the href points to an URL that refers to the select_item view with the correct parameter.

Upvotes: 3

Related Questions