[Fixed]-Populating backend script for Django form

1👍

The easiest way to interact directly is to leverage Ajax, whereby you use Ajax Post to send JSON to Django and then handle the arguments as a dict(). Here is an example:

In browser (JQuery/JavaScript):

    function newModule() {

        var my_data = $("#my_element").val(); // Whatever value you want to be sent.

        $.ajax({
            url: "{% url 'modules' %}",       // Handler as defined in Django URLs. 
            type: "POST",                     // Method.
            dataType: "json",                 // Format as JSON (Default).
            data: {
                path: my_data,                // Dictionary key (JSON). 
                csrfmiddlewaretoken: 
                         '{{ csrf_token }}'   // Unique key.
            },

            success: function (json) {

                // On success do this.

            },

            error: function (xhr, errmsg, err) {

                // On failure do this. 

            }

        });

In server engine (Python):

def handle(request):

    # Post request containing the key.  
    if request.method == 'POST' and 'my_data' in request.POST.keys():

        # Retrieving the value.
        my_data = request.POST['my_data']

    # ...

Now all you need to do is to direct your HTML form to call the JavaScript function and communicate the data to the engine.

To redirect the user to another page upon success, you can use this in your success function:

window.location.href = "http://www.example.com";

Which simulates a reaction similar to that of clicking on an anchor tag (link).

Hope this helps.

👤Pouria

Leave a comment