Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  119] [ 5]  / answers: 1 / hits: 24473  / 12 Years ago, wed, february 6, 2013, 12:00:00

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.


More From » python

 Answers
16

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.


[#80390] Tuesday, February 5, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hasanb

Total Points: 321
Total Questions: 102
Total Answers: 96

Location: Burkina Faso
Member since Fri, Sep 4, 2020
4 Years ago
;