如何通过django html按钮执行python代码?

use*_*137 3 html django django-views

我想通过onclick执行我的python代码.我在运行服务器后得到了结果.我的按钮不起作用.这是我的代码.

网址 -

url(r'^index/$', index),
Run Code Online (Sandbox Code Playgroud)

index.html-

<html>
<body>
  <form action="/index/" method="GET">
    <input type="submit" value="Click">
  </form>
  {{output}}
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

views.py -

from django.shortcuts import render, render_to_response
from pythoncode import mycode
def index(request):
    if request.method=="GET":
        py_obj=mycode.test_code(10)
        py_obj.code()
        return render(request, 'index.html', {"output":py_obj.a})
Run Code Online (Sandbox Code Playgroud)

我创建了另一个应用程序来分隔python代码 - 应用程序名称是python代码和文件名mycode

class test_code:
    def __init__(self, a):
        self.a=a
        self.b=4
    def code(self):
        return self.a, self.b
Run Code Online (Sandbox Code Playgroud)

请帮我.我是Django的新手.提前致谢

cez*_*zar 6

如果您只想在页面上单击并显示某些内容,则需要JavaScript和AJAX.无需仅为一个按钮创建整个表单.完全删除你的表格,结束标签也是错误的(阅读布兰登的评论).

您可以在index.html中使用此代码段:

<button id="myClickButton" type="button">Click</button>
<div id="myOutput"></div>
Run Code Online (Sandbox Code Playgroud)

现在让我们在点击按钮时触发:

$("#myClickButton").click(function() {
    $.get("/output/", function(data) {
        $("#myOutput").html(data);
    }, "html");
});
Run Code Online (Sandbox Code Playgroud)

上面的代码是jQuery.请阅读jQuery的官方文档.有一切都解释了如何使用该库.

现在我们来看看你的views.py.

def index(request):
    return render(request, 'yourapp/index.html')
Run Code Online (Sandbox Code Playgroud)

请记住将模板放在templates应用内的文件夹中.它应该如下所示:

--yourproject
|
|--yourapp
|----templates
|------yourapp
|--------index.html
Run Code Online (Sandbox Code Playgroud)

在views.py中创建另一个视图:

def output(request):
    if request.is_ajax():
        py_obj = mycode.test_code(10)
        return render(request, 'yourapp/output.html', {'output': py_obj.a})
Run Code Online (Sandbox Code Playgroud)

你的output.html可以是这样的:

<p>{{ output }}</p>
Run Code Online (Sandbox Code Playgroud)

就这样.没有头,没有身体,没有.此代码将在index.html中随时按AJAX插入.

现在让我们分析一下你的方法code:

def code(self):
    return self.a, self.b
Run Code Online (Sandbox Code Playgroud)

你知道这里发生了什么吗?您只能在函数中返回一个值.你认为你将a和b作为整数返回.错误!此方法返回包含两个元素的元组.这个方法会返回(10, 4).当你在索引视图中调用这个方法时,它只返回这个元组,但是你没有将它赋给变量,所以它会随风而去.这是无用的电话.

我希望这能让你了解如何做到这一点.如果您不想使用JavaScript(和AJAX),您可以按POST发送表单并在视图中进行区分:

def index(request):
    if request.method == 'GET':
        return render(request, 'yourapp/index.html', {'output': ''})
    elif request.method == 'POST':
        py_obj = mycode.test_code(10)
        return render(request, 'yourapp/output.html', {'output': py_obj.a})
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您将不需要视图输出和output.html.您可以将index.html与表单一起使用.