0

Hi I have this JavaScript function:

function calcscore(){
var score = 0;
$(".calc:checked").each(function(){
    score+=parseInt($(this).val(),10);
});
$("#price").text(score);
}

$().ready(function(){
$(".calc").change(function(){
    calcscore()
});
});

Now i want to call this calcscore() fucntion on views.py in Django. Say i have this function on my Views.py

def get_total():
try:
    final_cost =0
    final_cost = calcscore()
except:
    dummy_cost
return final_cost

Should i use ajax? or how can i achieve this?

Luke Luvevou
  • 81
  • 1
  • 9
  • 1
    you have wrong flow if you need call js inside python. – Sergey Miletskiy Oct 23 '18 at 07:09
  • Possible duplicate of [How do I integrate Ajax with Django applications?](https://stackoverflow.com/questions/20306981/how-do-i-integrate-ajax-with-django-applications) – Red Cricket Oct 23 '18 at 07:12
  • You can use js script inside your HTML template to do something over your HTML code, but it's a wrong way to call js in your python code. – Essex Oct 23 '18 at 07:38
  • You should wrap your head around the difference between front-end and back-end. You clearly haven't grasped this fundamental concept of web development yet, maybe it's a good time to take a step back and look it up? – dirkgroten Oct 23 '18 at 09:58

1 Answers1

1

You can't call javascript function from views.py. Because javascript runs on client side(browser) and views.py runs on backend side. for your case, you need to a view in views.py to return final_cost as a json or xml. javascript send a request to views using ajax to get final_cost. some articles about this.

https://www.codecademy.com/articles/back-end-architecture

https://hackernoon.com/in-simple-terms-backend-code-frontend-code-and-how-they-interact-2485c5a1bbd2

https://www.quora.com/How-do-front-end-and-back-end-technologies-work-together