'How to bind a function to an html button without a form in Django
I'm new to Django and I need to bind a function from python to a button using onclick from a file views.py. I saw a lot of discussions where they do this with forms, but I want to do without them
index.html:
<div class="submit">
<button type="button" name="submit" onclick="">Get Info</button>
</div>
views.py:
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
def get_info():
print("It works")
Need to bind get_info()
Solution 1:[1]
You can call your views directly,if are added in urls.py
<div class="submit">
<button type="button" name="submit" onclick="location.href='{% url 'get_info' %}">Get Info</button>
</div>
Solution 2:[2]
you can use fetche in Javascript to send HTTP request to the URL you want, in views.py
if request.method == 'POST': #or what method you have choosen
get_info()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | LordPokerFace |
Solution 2 | Ali fareeq |