skip to Main Content

I have a python script running in views.py within Django which returns two very large string arrays, x and y. It currently is able to run off a button press within my index.html.

def python_file(request):
    final()
    return HttpResponse("ran")

The ajax code I have running to do the button press.

<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

    <script>
            function gotoPython(){
                $.ajax({
                  url: "/python_file",
                 context: document.body
                }).done(function() {
                 alert('finished python script');
                });
            }
    </script>

It’s also attached to the URLS.py. I know there’s no array being returned right now, because I am unsure how to run the script, get the data simultaneously, then add it to the page without refreshing the page. So, I am asking what would be the best practice to do what I described. Any help would be appreciated.

2

Answers


  1. You can add parameters to the ajax.done(function) in order to get what your server returned.

     $.ajax({
                  url: "/python_file",
                 context: document.body
                }).done(function (response, textStatus, jqXHR) {
        // What happens when the call is successful (200 <= status code < 300 
        console.log(response); // Logs what you returned from your django 
        // x + "separator" + y
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
        // Status code over 400
    })
    .always(function (jqXHR, textStatus, errorThrown) {
        // Always happens
        ...
    });

    You can check ajax documentation here : https://api.jquery.com/jquery.ajax/#jQuery-ajax-settings-settings

    And your django view should return some text content :

    def view(response):
        // code
        return HttpResponse(status=200, content=x + "separator" + y)
    
    Login or Signup to reply.
  2. This is generally what I do, not sure if it’s best practice, but I return it with Json

    I included two examples, and POST and a GET.
    I also included some other stuff I usually return status and msg. When I catch an error or have an invalid POST I send back status = False and msg = '{error message}, then I can show that error message in the front end with Javascript. I keep this standardized in my project, but you do you.

    def python_file(request):
    
        xArray, yArray = final()
    
        import json
        data = {
            'status': True, #  True=All Good. False=Caught Error but didn't crash.
            'x': xArray,
            'y': yArray,
            'msg': 'returning x and y arrays',
        }
        return HttpResponse(
            json.dumps(data),
            content_type="application/json"
        )
    
    function gotoPython(){
        $.ajax({
            method: 'GET',
            url: '/python_file',
            success: function(data){
                console.log(data)
    
                if (data['status']){
    
                    // do things with arrays
                    data['x']
                    data['y']
    
                }else{
                    console.log('Server Replied with Error, but did not Crash');
                    console.log(data['msg']);
                };
            },
            error: function(event,xhr,settings,errorText){
                // general `xhr.status` Key for common errors
                // 0    = Server didn't Reply (Server Down)
                // 400  = Bad Request         (Syntax Error)
                // 403  = Forbidden           (Login Token Expired or not in Group)
                // 403  = Not Found           (Invalid Url)
                // 500  = Server Error        (Django Crash)
            },
        });
    };
    
    
    
    function gotoPythonWithData(){
        // if you wanted to POST data to this function you'd just do
        //   Note: Requires csrfmiddlewaretoken in template 
        //      Throw this anywhere (it's hidden): {% csrf_token %}
    
        submitData = {
            'return_item_count': 25,
            'csrfmiddlewaretoken': $('[name='csrfmiddlewaretoken']').val(),
        };
    
        $.ajax({
            method: 'POST',
            url: '/python_file',
            data: submitData,
            success: function(data){
                if (data['status']{
                    // do stuff
                }else{
                    console.log(data['msg']);
                };
            },
            error: function(event,xhr,settings,errorText){
            },
        });
    };
    

    Note: Some things like, Django Decimal objects, can not be be put into a Json Dump. In the Decimal example you’ve got to turn them into a Float or an Int

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search