Django: Is there any performance differences when using ajax? - django

I'm working on refactoring project in the middle of the work. There are a lot of context when view return render. I want to change it to get response when dom rendered using ajax.
I know it makes more request, but I wondered if there are any performance differences. If not, I want to do that.

According to my understanding, using AJAX and context are completely different methods.
AJAX does things on the client-side, while the Django context works on the server.
According to this basic difference, and considering the size of your page is large and multiple time changes, the AJAX is faster because you will only be requesting the data and not the whole page
But
If we assume the size of your page is large but data don't change frequently, the Django-Context is better in the scope of security and usability, because you will not expose the data that is to be rendered as it will be if used AJAX.
So it depends on your use case, if it's a static page then it is better to use django-context than AJAX and if it's a dynamic page use AJAX.

Related

Django REST framework is slow

I'm started using the Django REST framework in preparation for production, but unfortunately, it is performing quite slowly.
I am calling an array of 500 dictionaries, each with 5 key-value pairs each. In the shell, the call-time is not noticeable at all - you press enter, and it's done. Previously, when I was serving the same content directly without the REST framework, there was also no noticeable delay. However, with the REST framework, it takes about 1 - 2 seconds after the page has rendered for the content to display.
I do not think this is due to javascript as hitting the same details through the browseable API results in a similar delay.
Also, I am NOT cacheing at the moment.
There's no way anyone else is going to be able to debug this for you from the details given in the question.
Are you reusing an existing generic view or writing your own view?
Are you serializing the data, if so what does your serializer definition look like?
Does the issue manifest when rendering to JSON, or just when rendering to the Browsable API?
You mention serving the content without REST framework - what did the views looks like before, and what do they look like after?
The REST framework views are trivial, so use a profiling tool, or simply override them and add some timing. Likewise the renderers are trivial - subclass whatever renderer you're using at the moment, override .render() and add a couple of timing calls either side of calling the parent's .render() method.
If you think you've narrowed down a problem to a specific area then throw together a minimal test case and submit it as an issue.
The serialization itself is unlikely to be an issue, I've used the same serialization engine to replicate Django's fixture dumping and there was no significant degradation.
It's feasible that if you're doing lookups across model relationships you might need to add .select_related() or .prefetch_related() calls when constructing the queryset, exactly as you would with any other Django view.
Edit: Note that following on from this post there were significant serializer speed improvements made, as noted in this ticket.

CFWheels - Multi-step form?

I am wondering how one would setup a multi-step form in CFWheels.
Clearly I would need to store form data in the session etc as I go, but I would like to know the best approach from a wheels perspective to do this the 'wheels way'.
Do I have just one action in my controller that handles this? Or would it be best to seperate each part of the form out into separate actions?
Advise on this and possible code examples would be much appreciated.
Thanks,
Michael
The way I've done it in past is use Ajax calls and a jquery modal.
though the jquery modal is not important, I just like the aesthetic. a simple div replacement will also work.
If you cannot be sure that the users can use AJAX then it won't work for you, but you might be able to use a popup window.
The advantage of using Ajax calls for multi-step forms is that you can adjust the form content from one step to another. Another advantage is that you don't have to store user data in the cache or session. Because each time you send a form, you can use the POST or GET.
For this to work, the quickest way of setting this up is to use the plugin called RemoteFormHelpers. Then each step of the form would be a different controller (or the same one with a switch statement based on the data passed)
I think this is a pretty versatile way of doing this, but you cannot do a form that uses file-uploads, well not easily as ajax won't let you do it without some serious pain.

How to partially update a layout / template in Grails

I'm not really experienced with web development especially on views , I need a simple explanation (and pointers to a resource would be really nice as well) on how to deal with rendering a layout or a template partially without rendering whole page again...
What is the best practice?
Does Sitemesh layouts provide this? if so how ?
Shall I use JQuery pass the data as JSON from controller and update the corresponding div with ".html()" ? (which i did something like this a long time ago for some basic stuff, and think this is not really a grails way to do it)
or <g:include> does this for me?
Everything I read about this confused me even more :)
Actually the question is, what is the best practice in Grails to handle partial page updates (with Ajax or without ajax if there is any other ways these days)
Thanks in advance
EDIT:
this tutorial actually gives a really good idea of how to do it
What is the best practice?
The usual practice is to submit an AJAX request (i.e. a HTTP request triggered from JavaScript), and use a JavaScript callback function that updates a section of the page when a response is returned.
Does Sitemesh layouts provide this? if so how ?
When an AJAX request is received on the server-side, you could layout the response using Sitemesh in the same way that you can layout the response of a non-AJAX request. Sitemesh doesn't know or care what kind of request is being processed or whether it's laying out a whole page or just a fragment.
Shall I use JQuery pass the data as JSON from controller and update the corresponding div with ".html()"
Have a look at the tags provided by Grails that have the word "remote" somewhere in the tag name. They provide a very simple way to perform common AJAX tasks within a Grails application. For example, to submit an AJAX request to an action named bookByName and add the response to an element with id foo, simply add the following tag to your page.
<g:remoteFunction action='bookByName' update='foo'/>
Probably you need to use RemoteLink tag: http://grails.org/doc/latest/ref/Tags/remoteLink.html
You can configure it to update some fragment of your page, after calling an remote action.
BTW, it's grails way too, to use ajax and javascript, on client side :)

Who should format my data for display?

I have a django view, and this view returns a table which is populated asynchronously with an ajax call.
From the design point of view, which one should I follow:
the django view, called via ajax, returns the content of the table as a json response, containing html markups for each cell. The javascript callback handler takes the contents and slaps them untouched into the table cells.
the django view, called via ajax, returns pure data about what should go into the table, again as a json response. The async javascript callback takes the data, formats them with proper markup, and puts it into the table.
In other words, who should have the responsibility for markup formatting of the cell contents? the view or the javascript ?
I would be tempted to say the first, since the view already returns marked up content. If it returns a json containing marked-up content, there's not much difference.
I would like to hear your point of view.
If you're populating the whole table, you can put your table in its own template and return the table's html via ajax/json.
You'll need to edit the original template to include the table template:
{% include "myapp/_table.html" %}
And in the view, return the rendered template as a json variable, which your javascript will substitute in:
return { 'table': render_to_string("myapp/_table.html", context) }
This approach is good where you always want to update the entire table, and the rendering of the table doesn't require the full context. I'm not sure what the performance is like, but it is a clean way of updating part of the page, because you only define your table once.
It depends (as so often).
If the data is requested only here and now, it would be easier and less error prone to just let it render on server-side with the same set of templates that already rendered the standard view.
If you could think of use cases however, where the data would be needed in other places (like auto-complete fields), it would be better to let JavaScript do the job and create a clean, reusable JSON export.
These options add to all the other answers, and finally it's up to you to decide.
In a MVP system such as Django, the View decides what data should be shown, and the Presenter decides how it should be shown. Therefore the JavaScript should do the bulk of the formatting unless it proves intractably difficult to do so.
It is a good to practice Unabstrusive javascript, also called by some people as Hijax
So, you first have a standard page, that presents the table along with the rest of the page, with table in a particular django-template block.
Once you have this, you can include the extends part of the django template within an "if not ajax", so you only get the required table part in the ajax response which you can load in the client to the required div.
It is un-necessary and redundant to maintain the markup twice once at the server and once at the client, in javascript.
hence, I'd prefer the first option, of server redering, and client only loading the rendered html.
I've come across this several times before, and I generally opt for the latter, where the view returns pure JSON.
However, the approach you choose should definitely depend on several factors, one of which is targeted devices (and their CPU/network constraints). Pure JSON will generally result in smaller payloads and so may be optimal for mobile devices.
It may also make sense to expose both HTML and JSON versions of your content. This is especially helpful if you're looking to create a very lightweight API at some point for your site.
Finally, you can use a library such as John Resig's micro-templating or Closure Templates to simplify client-side HTML generation.
I would go with first choice, sine it presents more pros for user: page loads instantly (no wait for async call), no JS required (e.g. for mobile device)

where do functions that don't display go in django

I have some links on an html page like , , currently I handle them as so
<p> rate down
and have a url.py entry:
(r'^cases/(?P<case_id>\d+)/case_rate/(?P<oper>.)$', 'mysite.cases.views.case_rate'),
then I have a view function that handles the logic and hits the DB, then does this:
return HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))
I's there a better way to do this? I can see how this would be OK because it does have to redraw the screen to show the new rating...
The typical way to handle this is with an ajax request.
Instead of a link, you put a javascript handler that calls a view, wich updates the db, and returns a json / xml object with the new rating for the item. Then another javascript handle receives that response and updates the rating number on the screen, without a page reload.
Ideally, you'll keep both versions: plain html (the one you currently have) and the ajax one. The ajax one can be attach to the element after page load, so if javascript is not available, you'll still have a working site.
Then, regarding organization, you can have an "ajax" parameter on your view. The view should update the db accordingly, and if it's an ajax call, return the json / xml response, otherwise, return the new page. That way you can keep the logic (fetching the object, updating the db) on one place.
If you're asking whether case_rate should still go in the views.py given that it returns a redirect rather than providing content, the answer is yes, since case_rate is handling an request and returning a response.
But consider a situation where you had two view functions in views.py that had some duplicate code, and you chose to factor that duplicate code into another function that didn't both take request and return a response. Would that be fair game to leave in views.py? Sure, if moving it elsewhere would make the code harder to read. Or you might choose to put it elsewhere. It's really your call based on your sense of taste.