Django – How to Call Python Logic from JavaScript Without Additional Trigger

djangohtmljavascriptpythonview

I have been trying to solve this problem for sometime now. This is regarding django web development.

I have an HTML page which has a Javascript function to upload an image file from the users local computer. After that file has been uploaded on to the HTML template, I want to use the uploaded image file for further processing. I am calling my python logic from views.py for processing the image before rendering the processed information on to another HTML page.

My problem is that I want my upload function() to call my python logic.(There should be no additional trigger to call the python logic. i.e somefunction() within the upload function() which can directly call my python logic without having to use any button click or anything else.)

Can I somehow call the Python logic from javascript function (the one which uploads the image)? or should I save the uploaded file to my local computer and use its path to process the image information?

I googled and found that both of these are challenging tasks. There is no direct method to do it since one is client side scripting while the other is server side. Also, javascript does not have input output facilities (for writing/saving the uploaded image to local disk that too without a trigger).

What should be done in such a case? Should I write my upload function also in python then?(I don't want that to happen). Please help. Thanks in advance 🙂

Best Answer

If you want to call server-side logic from the client, you will have to make an HTTP (or other) request -- this can not be avoided. From what I understand as I read your question, an AJAX request may be what you're looking for.

See: https://www.w3schools.com/xml/ajax_intro.asp

If you're using jQuery: http://api.jquery.com/jquery.ajax/

Related Topic