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

问题描述 投票:3回答:1

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

网址 -

url(r'^index/$', index),

index.html-

<html>
<body>
  <form action="/index/" method="GET">
    <input type="submit" value="Click">
  </form>
  {{output}}
</body>
</html>

views.朋友 -

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

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

class test_code:
    def __init__(self, a):
        self.a=a
        self.b=4
    def code(self):
        return self.a, self.b

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

html django django-views
1个回答
6
投票

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

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

<button id="myClickButton" type="button">Click</button>
<div id="myOutput"></div>

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

$("#myClickButton").click(function() {
    $.get("/output/", function(data) {
        $("#myOutput").html(data);
    }, "html");
});

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

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

def index(request):
    return render(request, 'yourapp/index.html')

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

--yourproject
|
|--yourapp
|----templates
|------yourapp
|--------index.html

在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})

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

<p>{{ output }}</p>

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

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

def code(self):
    return self.a, self.b

你知道这里发生了什么吗?您只能在函数中返回一个值。你认为你将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})

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

© www.soinside.com 2019 - 2024. All rights reserved.