如何在单击按钮时调用Django函数?

2024-05-04 20:18:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个Django应用程序,我一直在思考如何在单击按钮时调用视图函数。

在我的模板中,我有一个链接按钮,如下所示,单击它会将您带到另一个网页:

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

单击按钮时,我还想调用Django视图函数(以及重定向到目标网站)。view函数增加数据库中的值,该值存储单击按钮的次数。

column_3_item.link_for_item是指向外部网站的链接(例如www.google.com)。现在,当这个按钮被点击,它会打开一个新的窗口,带你到谷歌网站。

我想做的是在单击按钮时调用Django视图函数,该按钮在不刷新页面的情况下更新数据库。我怎样才能做到这一点?


Tags: django函数视图模板数据库应用程序网页target
3条回答

以下答案可能有助于回答问题的第一部分:

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

这是一个纯javascript的极简方法。我使用JQuery,但您可以使用任何库(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>

替代方法

您可以通过以下方式更改链接,而不是放置JavaScript代码:

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

在你的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')))

我个人有两种可能的解决方案

1.不用表格

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

2.使用表格

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


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

其中url.py应该有这个

path('excel/',views1.downloadexcel,name="downloadexcel"),

相关问题 更多 >