Applying Javascript MVC architecture on existing backend MVC - django

We currently have a large implementation done in Django which mostly spit out static HTML. We are planning to implement a javascript modular framework to hook to django's API and define needed routes..etc
But, we do not want to scratch off what we did so far as the site is completely functional for non-js users. The more I read about JavaScript MVC designs, the more I find it impossible to implement the two to work together.
Any ideas of how to proceed in that direction? is there a best practice that someone can follow?

Keep what you got right now as a fail-safe. Create new, separate views meant for Ajax requests that handle the processing of data and respond with appropriately formatted respond data (XML, JSON etc.).
Basically, Django is your model. Any action defined by your Javascript controller can either modify the model or the view.
If it modifies the view, there are two options: you either change just the display of data, and thus you just call a Javascript function that alters the HTML, or you display new data. In that case, you have to create a Django view that supplies that data in a format that Javascript can process easily. In your Ajax request, supply a callback (the view part of your Javascript) that handles displaying that data.
If the action modifies the model, you also need to create a Django view that processes the POST data sent by the Ajax request as needed, and returns either the error messages or a success message in a format that is, again, easily processed by Javascript. Again, you should register a callback to your Ajax request that handles the display of the messages returned by Django.
So basically, the only change to your current views would be that you supply the appropriate Javascript code to map the actions to Ajax requests and to handle the data returned by Django for your Ajax requests. Everything else should be done in separate Django views.

Related

Is there a way in django to update the same page with the response without totally rendering it?

Is there a way in django to update the same page with the response without totally rendering it. I am trying to create a code editor to test. But when I am returning the results my contents are removed. I understand it is because I am rendering the page . I need the contents to retain. How can I do it using redirect? I am including the render statement I used and a screenshot of how it looks here:
Steps:
Handle post request
Program execution code
Save the result in a variable called "message". Then I used
return render(request, 'editor.html', {'message': message})
I want to redirect the message to the same page without rendering a new page.
[Before submission][1]
[After submission][2]
[1]: https://i.stack.imgur.com/BxoLU.png
[2]: https://i.stack.imgur.com/uiEOU.png
Any help will be appreciated. Thank you.
it is possible. using ajax in front-end and render or render_to_string in back-end(Django). using ajax you're able to call a url (with/without data you want to send), then in the views.py you can do anything needed and return render(request,'template.html, context). then in ajax you have success: function (res) { $('#id_of_element').append(res)}. this function in ajax will append the recived response which is a rendered HTML template to the target element.
For that, you have to switch to a different web software paradigm called "single page application", which implies that both, backend and frontend, are functional software components on their own, instead of having a "dumb" HTML frontend that only displays what the backend renders.
In a regular web application, the front end is served from a backend with all the information that is going to display. In a Single Page Application, the front end is served by a server independent of the backend server, and the frontend and backend interact through an API served by the backend.
With this architecture, the frontend component is responsible for requesting and providing data from and to the backend, as well as for displaying the data and getting user's interaction, and the mean for interchanging data with the backend is called an ajax, that is an asynchronous request.
The only language accepted by web browsers is javascript, but there are many frameworks and second level languages that can render a javascript application, like React, Angular, Vue, and many others.

Django - load new objects via ajax

In django app I need to periodically check for if new object of particular model are created.
I want to this by ajax.
I was thinking about something like this:
render current timestamp into template, load current objects.
Then, every x seconds do ajax request and ask for objects which are created later then this timestamp.
What do you think? Is there maybe a better way?
What you want is a way for the client to know whether something has changed in the server. Generally there are three ways to stimulate this subscriber/broadcaster, or pull/push, relationship. The first is Ajax long-polling, which is roughly what you described. The second is implemented via WebSocket, which unfortunately not all browser supports. The third is HTTP streaming, or a long polling at the HTTP level. All three are available in https://github.com/ziyan/django-comet
A newer technology is Webhooks, which allows you to subscribe to server changes via URL (http://en.wikipedia.org/wiki/Webhook). Check it out here for an early Django adaptation: https://github.com/johnboxall/django_webhooks

How django and ExtJS passing data to each other by JSON?

I am new to web development, recenlty I am learning to build a webserver using django + ExtJs. but I am confusing about how to use django + ExtJS together.
For django, it has template to display the data, the parameter passing to html files could be dict, and could send JSON. I am trying to use it as the backend of the webserver.
ExtJS, support JSON.
Then here comes myquestion:
How to make .html files( used by django as the template layer) to accept "JSON"? It seems that ExtJS has no ability of sending json data through socket or other IPC.
It seems that ExtJS has the ability to use AJAX to "post" the data to backend, however, I am not sure how the .html could get data from backend using JSON? I downloaded ExtJS the 4.2.1 version, and find some examples in the files, however, it only give some example to get data from "json files".
Can someone give me an example or show me which aspect I should learn or explain its mechanism briefly?
This is done not at template layer, but at view level. You should write a view function in Python and assign it to some URL address. In that view function, you can access JSON data sent by ExtJS and process it how you wish.
I totally misread your question, here's the updated answer:
On Django side, you should write a view function, which would return JSON response, and assign that view to some URL address. (See How to write a view in Django documentation, if you're new to this.)
On ExtJS side, you should make an Ajax request to that URL, and provide success callback function that will be able to access the output of Django view function. (Seems like Ajax requests in ExtJS are usually done using Ext.Ajax.request.)

How to prevent Django pages from refreshing after submit?

I am using the Django template system. What I want is, when I submit a form, or click to an url link, page does not refreshes, but loads with the data returning from the server. Is it possible?
I recommend a combination of jQuery (easy, powerful, popular javascript library) and dajax/dajaxice (http://www.dajaxproject.com/). Dajax is very easy to set up and use, and jQuery is also easy to set up and use. Dajax is strictly for AJAX communications through Django. jQuery is perfect for taking a simple site and making it more fluid, intuitive, and user-friendly.
You need JavaScript to do that. What you are looking for is called AJAX (Asynchronous JavaScript and XML). Essentially, it means you use JavaScript to send a request to the server as soon as the link/button is clicked. The server returns some data to your Script, which then can be used to manipulate the HTML page, e.g. by inserting the responded data into the DOM. Since you do everything with JavaScript, no reloading of the whole page is required.
To start, read the AJAX tutorial. There are certain JavaScript libraries that make these things more simple for you (e.g. jQuery), but you really should understand how this stuff works first, since else you might get into trubble while trying to debug it.

Plone-like search box in Django?

Plone has a beautiful search box with a "Google suggest" like functionality for its site. It even indexes uploaded documents like PDFs. Does anyone know of a module that can provide this kind of functionality in a Django site?
Plone implements it's LiveSearch feature by maintaining a separate metadata table of indexed attributes (fields such as last modified, creator, title are copied from the content objects into this table). Content objects then send ObjectAdded/ObjectModified/ObjectRemoved events, and an event subscriber listens for these events and is responsible for updating the metadata table (in Django events are named signals). Then there is a Browser View exposed at a fixed URL that searches the metadata and returns the appropriate LiveSearch HTML, and finally each HTML page is sent the appropriate JavaScript to handle the autocomplete AJAX functionality to query this view and slot the resulting HTML results into the DOM.
If you want your LiveSearch to query multiple Models/Content Types, you are likely going to need to send your own events and have a subscriber handle them appropriately. This isn't necessary for a smaller data sets or lower traffic sites, where the performance penalty for doing multiple queries for a single search isn't a concern (or you only want to search a single content type) and you can just do several queries from your View.
As for the JavaScript side, you can roll-your-own or use an existing JavaScript library. This is usually called autocomplete in the JS library. There is YUI autocomplete and Scriptaculous autocomplete for starters, and likely lots more JavaScript autocomplete implementations out there. Plone uses KSS for it's JavaScript library, the KSS livesearch plugin is a good place to start if looking for example code to pluck from.
http://pypi.python.org/pypi/kss.plugin.livesearch
And a tutorial on using KSS with Django:
http://kssproject.org/docs/tutorial/kss-in-django-with-kss-django-application
KSS is quite nice since it cleanly separates behaviour from content on the client side (without needing to write JavaScript), but Scriptaculous is conceptually a little simpler and has somewhat better documentation (http://github.com/madrobby/scriptaculous/wikis/ajax-autocompleter).