53

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 it takes you to a different webpage:

<a target="_blank" href="{{ column_3_item.link_for_item }}">Check It Out</a>

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

The column_3_item.link_for_item is a link to an external website (e.g. www.google.com). Right now when that button is clicked, it opens a new window which takes you to the 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. How I can achieve this?

daaawx
  • 3,273
  • 2
  • 17
  • 16
Dev
  • 1,529
  • 4
  • 24
  • 36
  • 1
    I don't understand your question. Your code calls the view function at whatever `column_3_item.link_for_item` is mapped to in your urlconf. – Daniel Roseman Mar 11 '13 at 14:40
  • adding to Daniel's comment: if you need to click -> "real time" update the couter, without refreshing the page, you may need to rewrite your question. If you have a view pointing to that link, you already have what you need – Samuele Mattiuzzo Mar 11 '13 at 14:48
  • sorry for the confusion. the `column_3_item.link_for_item` is a link to an external website (example:- www.google.com). 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. – Dev Mar 11 '13 at 14:49
  • have you looked at https://docs.djangoproject.com/en/dev/topics/class-based-views/mixins/#more-than-just-html – dmg Mar 11 '13 at 15:18
  • 1
    you can do it in many ways, but if you do not want to reload/change the page I think you have to rely on javascript (e.g. making an ajax call to the view that updates the counter from the same tag you use for opening the new page). Is using javascript an issue? – furins Mar 11 '13 at 15:26
  • @furins - Could you please give an example how i can do it with javascript. Sorry to ask this, i am just new to web development. – Dev Mar 11 '13 at 15:52
  • [Read the Django tutorial, it has all the information you need](https://docs.djangoproject.com/en/dev/intro/tutorial03/#write-your-first-view) –  Mar 11 '13 at 16:44

3 Answers3

59

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

<html>
    <head>
        <title>An example</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script>
            function call_counter(url, pk) {
                window.open(url);
                $.get('YOUR_VIEW_HERE/'+pk+'/', function (data) {
                    alert("counter updated!");
                });
            }
        </script>
    </head>
    <body>
        <button onclick="call_counter('http://www.google.com', 12345);">
            I update object 12345
        </button>
        <button onclick="call_counter('http://www.yahoo.com', 999);">
            I update object 999
        </button>
    </body>
</html>

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 column_3_item.pk %}/?next={{column_3_item.link_for_item|urlencode:''}}">
    Check It Out
</a>

and in your views.py:

def YOUR_VIEW_DEF(request, pk):
    YOUR_OBJECT.objects.filter(pk=pk).update(views=F('views')+1)
    return HttpResponseRedirect(request.GET.get('next'))
furins
  • 4,979
  • 1
  • 39
  • 57
  • Thanks very much. I used the alternative approach and it worked perfectly as expected. – Dev Mar 11 '13 at 18:51
  • 3
    The point of using Django is to eliminate using other languages. I'm sorry for js but if you're using Django when a button is clicked we want to trigger using Django but not js. Please help me! – Mohith7548 May 18 '19 at 10:04
  • 8
    @KuneMohith then please follow the alternative approach, it does not require javascript. Apart from that, I do not believe that the point of Django is to eliminate using other languages. You cannot run "django" (python) on client side. – furins May 18 '19 at 11:42
  • 1
    `HttpResponseRedirect(request.GET.get('next')))` is containing one ')' to much at the end. – The_spider Dec 21 '21 at 20:36
  • @The_spider fixed, thank you! – furins Dec 22 '21 at 21:13
25

There are 2 possible solutions that I personally use

1.without using form

 <button type="submit" value={{excel_path}} onclick="location.href='{% url 'downloadexcel' %}'" name='mybtn2'>Download Excel file</button>

2.Using Form

<form action="{% url 'downloadexcel' %}" method="post">
{% csrf_token %}


 <button type="submit" name='mybtn2' value={{excel_path}}>Download results in Excel</button>
 </form>

Where urls.py should have this

path('excel/',views1.downloadexcel,name="downloadexcel"),
nofoobar
  • 2,826
  • 20
  • 24
5

The following answer could be helpful for the first part of your question:

Django: How can I call a view function from template?

Community
  • 1
  • 1
Mahshid Zeinaly
  • 3,590
  • 6
  • 25
  • 32