2

I want to call a python function in the backend without reloading the page. Like this:

index.html

<button name="button" onclick="run_function(param1, param2)">Run</button>

views.py

some_function(param1, param2):

    return(param1, param2)

Please don't answer with "learn the whole django documentation by hard!" i have already done some research, however I havn't quiete found any working code for my case.

3
  • You would need to use Ajax. And no, this has nothing to do with the Django documentation. Commented Dec 2, 2019 at 13:55
  • I am aware of that, however every javascript7ajax code I tried that was posted online and on stackoverwflow never really worked for me. And I don't really want to study the whole ajax, js and jquery docuimentation either. Commented Dec 3, 2019 at 8:28
  • Well unfortunately you are going to have to learn if you want to do this. Commented Dec 3, 2019 at 8:55

2 Answers 2

4

So at last I solved this issue myself. This helped alot.

index.html

<button name="button" onclick="run_function(param1, param2)">Run</button>

script.js

function run_function(param1, param2){
    console.log("running");
    $.ajax({
        url : "random_url/", // the endpoint
        type : "GET", // http method
        data : { param_first : param1, 
                param_second : param2 }, // data sent with the get request

        // handle a successful response
        success : function(json) {
            console.log("success"); // another sanity check
        },

        // handle a non-successful response
        error : function(xhr,errmsg,err) {
            console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
        }
    });
};

views.py

from django.http import HttpResponse
import json

def some_func(request):
    if request.method == 'GET':
        param1 = request.GET.get('param_first')
        param2 = request.GET.get('param_second')
        print(param1, param2)


        response_data = 'successful!'

        return HttpResponse(
            json.dumps(response_data),
            content_type="application/json"
        )

    else:
        return HttpResponse(
            json.dumps({"nothing to see": "this isn't happening"}),
            content_type="application/json"
        )

urls.py (don't know if this step was necessary)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('random_url/', some_func)
]

Also make sure that you got the uncompressed jquery package.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi. Where does the json come from in script.js?
@TheSprinter in the views.py you see inside the function an HttpResponse function that sends out a json response.
0

The python code is actually running on the server. That's why you need to "reload" the page to make a python code run. Actually, when you do that, you are sending a request to the server, which will run the python code and will return you a proper populated HTML page as a response.

If you want to run some code from the browser, you can use JavaScript to define a function that will be called when a click event is triggered.

More info on:

Article about Client-Server architecture

Introduction to JavaScript

1 Comment

can you write me an example code. I could use ajax. I am aware of that, however every javascript7ajax code I tried that was posted online and on stackoverwflow never really worked for me. The links you posted are not really useul and not rreally specific to my problem with django.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.