如何在按钮单击时调用Django函数? [英] How do I call a Django function on button click?
问题描述
我正在尝试编写Django应用程序,而我却被困在单击按钮时如何调用视图函数。
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>
单击按钮时,我还想调用Django视图函数(以及重定向)到目标网站)。视图函数增加数据库中存储该按钮被单击次数的值。
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.
column_3_item.link_for_item
是指向外部网站(例如 www.google.com )的链接。现在,单击该按钮时,它会打开一个新窗口,该窗口将带您进入Google网站。
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.
我想做的是也调用Django视图函数单击该按钮时,将更新数据库而不刷新页面。我如何实现呢?
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?
推荐答案
这是一种纯JavaScript的简约方法。我使用JQuery,但您可以使用任何库(甚至根本没有库)。
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>
替代方法
代替放置JavaScript代码,您可以通过以下方式更改链接:
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>
并在您的 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')))
这篇关于如何在按钮单击时调用Django函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!