Home > Software engineering >  How to bind a function to an html button without a form in Django
How to bind a function to an html button without a form in Django

Time:05-13

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 >
      <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()

CodePudding user response:

You can call your views directly,if are added in urls.py

<div >
      <button type="button" name="submit" onclick="location.href='{% url 'get_info' %}">Get Info</button>
</div>

CodePudding user response:

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()
  • Related