35

I have a question on how to call a view function from a template HTML button? Like an onclick function? Here is the template:

<input id="submit" type="button" onclick="xxx" method="post" value="Click" />

And the views.py is:

def request_page(request):
    ...do something...
    return render_to_response("/directory.html", {})

Thank you very much.

Robert
  • 2,189
  • 6
  • 31
  • 38

6 Answers6

114

Assuming that you want to get a value from the user input in html textbox whenever the user clicks 'Click' button, and then call a python function (mypythonfunction) that you wrote inside mypythoncode.py. Note that "btn" class is defined in a css file.

inside templateHTML.html:

<form action="#" method="get">
 <input type="text" value="8" name="mytextbox" size="1"/>
 <input type="submit" class="btn" value="Click" name="mybtn">
</form>

inside view.py:

import mypythoncode

def request_page(request):
  if(request.GET.get('mybtn')):
    mypythoncode.mypythonfunction( int(request.GET.get('mytextbox')) )
return render(request,'myApp/templateHTML.html')
Sarthak Agrawal
  • 321
  • 4
  • 17
Mahshid Zeinaly
  • 3,590
  • 6
  • 25
  • 32
  • 2
    This is a very good answer - surprised no more votes... Have you used this in your own projects? – nicorellius Feb 09 '14 at 19:52
  • 1
    I am glad it was useful. Yes I have a project uploaded at Github where I used it. https://github.com/MahshidZ/ArchivIT – Mahshid Zeinaly May 28 '14 at 00:30
  • 1
    Take care, GET and HEAD request should be safe/idenpotent. https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html – Eloims Nov 13 '16 at 11:44
  • 4
    What about {% csrf_token %} after input ? – Danielius May 13 '17 at 00:38
  • How do I have to change the url file? – Uwe.Schneider Apr 17 '22 at 13:45
  • As @Danielius mentioned, I had to add `{% csrf_token %}` inside the `
    ` tag. Additionally, I used `
    ` and found success by invoking `request.POST.get("buttonname")`, in case this helps anyone else. I did this because it was confusing having the `GET` request method, then also invoking the `.get()` method.
    – Daggerpov May 31 '23 at 20:22
17

One option is, you can wrap the submit button with a form

Something like this:

<form action="{% url path.to.request_page %}" method="POST">
    <input id="submit" type="button" value="Click" />
</form>

(remove the onclick and method)

If you want to load a specific part of the page, without page reload - you can do

<input id="submit" type="button" value="Click" data_url/>

and on a submit listener

$(function(){
     $('form').on('submit', function(e){
         e.preventDefault();
         $.ajax({
             url: $(this).attr('action'),
             method: $(this).attr('method'),
             success: function(data){ $('#target').html(data) }
         });
     });
});
karthikr
  • 97,368
  • 26
  • 197
  • 188
  • 3
    Yeah.. thats what the ajax submit is doing. your question was unclear, so i added both the answers – karthikr Jul 11 '13 at 18:26
  • I wonder is there any way for doing multithreadings in Django? Here is the questions: http://stackoverflow.com/questions/17601698/can-django-do-multi-thread-works – Robert Jul 11 '13 at 19:26
  • [Django-Notification](https://github.com/pinax/django-notification) could be what you are looking for. What does this have to do with this question anyways ? – karthikr Jul 11 '13 at 19:29
  • @karthikr you'll have to change your input in the first snippet to type="submit" – Kelsey Dec 30 '16 at 03:01
  • Where do I put the code for the submit listener? – Uwe.Schneider Apr 17 '22 at 13:46
12

How about this:

<a class="btn btn-primary" href="{% url 'url-name'%}">Button-Text</a>

The class is including bootstrap styles for primary button.

mapadj
  • 181
  • 2
  • 3
5

you can put the input inside a form like this:-

<script>
    $(document).ready(function(){
        $(document).on('click','#send', function(){
            $('#hid').val(data)
            document.forms["myForm"].submit();
        })
    })
</script>

<form id="myForm" action="/request_page url/" method="post">
    <input type="hidden" id="hid" name="hid"/>
</form>
<div id="send">Send Data</div>
Kousik
  • 21,485
  • 7
  • 36
  • 59
5

For deleting all data:

HTML FILE

  class="btn btn-primary" href="{% url 'delete_product'%}">Delete

Put the above code in an anchor tag. (the a tag!)

url.py

path('delete_product', views.delete_product, name='delete_product')]

views.py

def delete_product(request):
    if request.method == "GET":
        dest = Racket.objects.all()
        dest.delete()
        return render(request, "admin_page.html")
bagerard
  • 5,681
  • 3
  • 24
  • 48
Kunal Karnik
  • 51
  • 1
  • 3
4

For example, a logout button can be written like this:

<button class="btn btn-primary" onclick="location.href={% url 'logout'%}">Logout</button>

Where logout endpoint:

#urls.py:
url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'),
Nitwit
  • 291
  • 3
  • 13
Lucian
  • 874
  • 11
  • 33