I am trying to add some basic dynamic functionality to a web page. How do I use JavaScript on the client side to access database information via django on the server side?
I feel like it should be easy to have a JavaScript function on the webpage which calls a django view (or something) and the django view returns a value to the JavaScript function. I don’t want the JavaScript itself to connect to the database, because that would seem to circumnavigate django (which, to me, seems incorrect).
Further, I want to be able to do several database requests via JavaScript on a single page. An example would be a web page for creating an invoice. Every additional line of the invoice would require a new query to the database. Then, depending on the product added to the invoice, an additional query would be required to determine that product’s price. What I’m getting at is multiple queries to the database within one page done dynamically.
Basically, I want django to do the database searching and pass the information to JavaScript.
To put some “standard” terms to what you’re asking – it sounds like you’re looking for AJAX functionality from Django.
First, the bad news: There aren’t any Django features specific to this kind of functionality.
The good news:
The Django view you’re talking about will accept HTTP requests just like any other. What you need to do is write some JavaScript code that generates its own HTTP request and consumes the output of the view just like a browser would.
The better news:
There are JavaScript libraries like JQuery that make writing reliable client side asynchronous requests (what you want) a lot simpler. In fact, I’d strongly advocate using a library like JQuery over trying to write your own request processing code. It’s a simple problem to get working reliably on one browser/machine, but incredibly difficult and time consuming to get working reliably across all of today’s widely-used browsers.
Hope this helps!