Dev Dev - 11 months ago 55
Python Question

how to call a django function on button click

I am trying to write a Django application and i am stuck at how i can call a view function when a button is clicked.

In my template, i have a link button as below when clicked takes you to a different webpage.

<a target="_blank" class="btn btn-info pull-right" href="{{ column_3_item.link_for_item }}">Check It Out</a>

When the button is clicked, i want to call a Django view function also (along with re-direct to a target website). The view function is to increment the value in the database which stores the number of times the button is clicked.

Could anyone please help me how i can achieve this.

Edit :-

sorry for the confusion. the column_3_item.link_for_item is a link to an external website (example:- Right now when that button is clicked, it opens a new window which takes to google website. what i would like to do is to call a django view function also when the button is clicked which updates the database without refreshing the page.



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