How do I call a Django function on button click?

前端 未结 3 1483
走了就别回头了
走了就别回头了 2020-12-02 10:10

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, w

相关标签:
3条回答
  • 2020-12-02 10:28

    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"),
    
    0 讨论(0)
  • 2020-12-02 10:39

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

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

    0 讨论(0)
  • 2020-12-02 10:43

    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')))
    
    0 讨论(0)
提交回复
热议问题