How to execute python code by django html button?

后端 未结 1 1444
猫巷女王i
猫巷女王i 2021-01-05 18:45

I want to execute my python code by onclick. I am getting result after running the server. My button is not working. Here is my code.

URL -

url(r\'         


        
相关标签:
1条回答
  • 2021-01-05 19:20

    If you just want to click and display something on the fly on your page, you'll need JavaScript and AJAX. There is no need to create whole form just for one button. Remove your form completely, which closing tag is also wrong (read Brandon's comments).

    You can use this snippet in your index.html:

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

    Now let's trigger something when clicking on the button:

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

    The above code is jQuery. Please read the official documentation of jQuery. There is everything explained how to use the library.

    Now let's go to your views.py.

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

    Remember to put your templates in a folder templates within your app. It should look like this:

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

    Make another view in your 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})
    

    Your output.html can be like this:

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

    That's all. No header, no body, nothing. This code will be inserted per AJAX on the fly in index.html.

    Now let's analyze your method code:

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

    Do you know what happens here? You can return only ONE value in a function. You think you're returning a and b as integers. Wrong! This method returns a tuple with two elements. This method will return (10, 4). When you call this method in your index view it just returns this tuple, but you're not assigning it to a variable, so it will go with the wind. It's useless call.

    I hope this gives you an idea how you can do it. If you don't want to use JavaScript (and AJAX) you can send your form per POST and make a distinction in your view:

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

    In this case you won't need the view output and output.html. You can use your index.html with the form inside.

    0 讨论(0)
提交回复
热议问题