Django:如何从模板调用视图函数? [英] Django: How can I call a view function from template?

查看:1136
本文介绍了Django:如何从模板调用视图函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于如何从模板HTML按钮调用视图功能的问题?像一个onclick功能?
这是模板:

 < input id =submittype =buttononclick =xxx method =postvalue =点击/> 

而且,views.py是:

  def request_page(request):
...做某事...
返回render_to_response(/ directory.html,{})

非常感谢。

解决方案

一个选项是,您可以使用表单

$ b $包装提交按钮b

这样的一个例子:

 < form action ={%url path.to.request_page %}method =POST> 
< input id =submittype =buttonvalue =点击/>
< / form>

(删除 onclick 方法



如果你想加载页面的特定部分,没有页面重新加载 - 你可以做

 < input id =submittype =buttonvalue =点击data_url /> 

提交监听器

  $(function(){
$('form')。on('submit',function(e){
e.preventDefault();
$ .ajax({
url:$(this).attr('action'),
方法:$(this)方法'),
success:function(data){$('#target')。html(data)}
});
});
});


I have a question on how to call a view function from a template HTML button? Like an onclick function? Here is the template:

<input id="submit" type="button" onclick="xxx" method="post" value="Click" />

And the views.py is:

def request_page(request):
    ...do something...
    return render_to_response("/directory.html", {})

Thank you very much.

解决方案

One option is, you can wrap the submit button with a form

Something like this:

<form action="{% url path.to.request_page %}" method="POST">
    <input id="submit" type="button" value="Click" />
</form>

(remove the onclick and method)

If you want to load a specific part of the page, without page reload - you can do

<input id="submit" type="button" value="Click" data_url/>

and on a submit listener

$(function(){
     $('form').on('submit', function(e){
         e.preventDefault();
         $.ajax({
             url: $(this).attr('action'),
             method: $(this).attr('method'),
             success: function(data){ $('#target').html(data) }
         });
     });
});

这篇关于Django:如何从模板调用视图函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆