Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Javascript call a Django method/function?

Imagine a simple page with a counter and two buttons. The value displayed by the counter is a read/stored in a model's field. I want that when I press the "green" button the counter is incremented by one and when I press the "red" button the counter is decreased by one. What's the best way to implement such behavior:

  1. Button calls model's method (Django method) which updates the model's field (DB write); Entire page is refreshed and the counter display updated (DB read).
  2. Button calls javascript function which updates the counter display (JS/HTML); In the background, a model's method (Django method) is called to update the model's field (DB write).
  3. Yet another way?

Can the javascript code call a Django function? I'm a newbie at Django (I followed the tutorial up to part 4). I already understood the MVC/MTV concept and the data read/write/display, but what's bothering me now is introducing behavior/interactivity on my pages.

like image 471
dialex Avatar asked Nov 28 '22 02:11

dialex


1 Answers

JavaScript in browser-side is sitting on the front end, while Django is serving on the backend(server-side). The former can neither nor need to directly call the latter's functions. The interface between them is typically web service APIs, namely, browser that makes AJAX calls with URLs defined in web services, which are backed by Django.

More specifically, JavaScript sends HTTP requests to web server, in turn Django's URL dispatcher maps the request URLs to corresponding Django views(function-based or class-based). In short, a typical route can be simplified as:

JavaScript -> HTTP request -> Django URL dispacher(mapping rules are in urls.py or urls/XXX.py) -> Django view function(views.py or views/XXX.py) -> Django form(optional) -> Django model(optional).

For more Django technical details, you may refer to Django tutorial or Practical django Projects.

Final word: even if JavaScript could call Django function method/function, it should be avoided. From web service's perspective, Django methods/functions are only implementation detail, which are more subject to change(compared to web service API). Backend developers may change function name, switch to some framework other than Django, or even change programming language like Java, Ruby or PHP for whatever reason.

like image 129
Hui Zheng Avatar answered Dec 05 '22 09:12

Hui Zheng