Reputation: 43
I've recently started learning how to use Django and I was wondering whether or not you could create a button in HTML that can directly call a python function without changing the URL. I was told this was possible with JS but I wanted to know if you could do that in Python.
Thanks for your time reading this!
Upvotes: 0
Views: 294
Reputation: 709
A potential option if you're not ready to dig deep into javascript is to look into HTMX.
You can just create a django view with whatever python functionality you want, and use HTMX to perform a get or post call to it. Here I'm just returning a chunk of html that will be inserted into the dataLocation
div, but you could literally call anything that's possible with python from your view and return useful html.
index.html
<button hx-get="/alert_message/" hx-target="#dataLocation" hx-swap="innerHTML">
Click Me
</button>
<div id="dataLocation"></div>
views.py
from django.http import HttpResponse
def alert_message(request):
return HttpResponse(
(
"<div class='alert alert-warning'>"
" <strong>Warning!</strong> Some important message."
"</div>"
),
status=200,
content_type="text/html",
)
urls.py
urlpatterns = [
path('alert_message/', views.alert_message, name='alert_message'),
]
Upvotes: 1
Reputation: 109
Depending on your application you may want to look into Django forms. Otherwise JS (ajax) is the way to go. More details could always help.
Upvotes: 0