How to Call a Django Function on Button Click

How do I call a Django function on button click?

here is a pure-javascript, minimalistic approach. I use JQuery but you can use any library (or even no libraries at all).

<title>An example</title>
<script src=""></script>
function call_counter(url, pk) {;
$.get('YOUR_VIEW_HERE/'+pk+'/', function (data) {
alert("counter updated!");
<button onclick="call_counter('', 12345);">
I update object 12345
<button onclick="call_counter('', 999);">
I update object 999

Alternative approach

Instead of placing the JavaScript code, you can change your link in this way:

<a target="_blank" 
class="btn btn-info pull-right"
href="{% url YOUR_VIEW %}/?next={{column_3_item.link_for_item|urlencode:''}}">
Check It Out

and in your

def YOUR_VIEW_DEF(request, pk):
return HttpResponseRedirect(request.GET.get('next'))

Call Django on HTML button click

you need to wrap your <button> with <form> tag, as following snippet:

<form action='actionUrl' method='GET'>
<button type='submit'> sort me</button>

and in your module you should point the actionUrl with specific view from the module as follow:

from django.urls import path

from . import views

urlpatterns = [
path(actionUrl, views.yourSort),

you should more read about request lifecycle on Django:

  1. user submit request
  2. Django tries to get the first match between request's URL and routes defined in
  3. the request is passed to the matched view
  4. the view get executed, usually this some model processing
  5. a response (template) is returned by the view as HttpResponse

Django: call a view function via a button click

The button element with type="button" does not send the form. Either set the type to "submit":

 <button type="submit">RESIGN</button>

Or remove the type:


Running django view/function on button click

In your template link to the view you want:

<a href="{% url 'myapp:myview' %}" class="btn btn-success">Accept</a>

Of course you can also pass a pk or other data to the url if you need to.

Django - call def on button click?

If you want something to be rendered back, must return render -
return render(request, 'your-template.html',{}), so it will be

from django.shortcuts import render

def print_from_button(request):

print( int(request.GET.get('mytextbox')) )
print('Button clicked')
return render(request, 'your-template.html',{'value':'Button clicked'})

Then on the client side - in the inspector's console, or whatever tool you use, you'll see 'Button clicked' set in value.
Make sure your-template.html (or whatever name you prefer) exists in the templates directory configured for your Django project.

How do I call a Django function without button click

for example..

in your views :

def PageView(request):
return render(request, 'yourhtml.html', {'variable_name': 'Value Of Variable'})

and in your html page:

<p> {{ variable_name }} </p>

and it will return <p> Value Of Variable </p>

Related Topics

Leave a reply