Tajinder Singh
Tajinder Singh

Reputation: 1531

Call a Django python function from tag script in the template

This is some content of my Django template.

...
<a id="ID" href="">Do operation with database.<a/>
...
<script type="text/javascript">
                    window.onload = function () {
                        var a = document.getElementById("ID");
                        a.onclick = function () {
                            if (confirm("do you really want to perform task?")) {
                                /** call python function in order to perform some operations with database **/
                            }
                            return;
                        }
</script>
...

The function is for example(we can imagine the function is in views.py):
def performtask():
#do my operation with the database

My question is, how it is possibile to call performtask() function from the script tag in my template?

Upvotes: 1

Views: 1609

Answers (1)

Somil
Somil

Reputation: 1941

you should go through with ajax

   $.ajax({
        url: "http://abc,com/app/",
        type: "POST",
        data :{},
        success:function(result){
            //your code
        },
        error:function(error){
            //error handal
        }
    });

you can get more details here :

https://realpython.com/blog/python/django-and-ajax-form-submissions/

https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html

Upvotes: 1

Related Questions