django call to custom method in model when rendering the page - django

If I have a custom method in my Model that I am calling in my template, does it mean there are multiple roundtrips happening from client(browser) to server?
I am pretty sure when I return render() from my view, rendering happens on the server side and the output as HTML is returned to the client.
Please correct me if my understanding is off.

Django renders at server side
Rendering happens at server side. If you thus write {{ foo.bar }} in your template, the client never knew that there was a foo.bar in the template. Substituting tags, etc. by (HTML)output is done by the Django render engine.
The result of that rendering is given to the client through a HTTP response. So the response itself, does not contain the render logic, it contains the "product" of the rendering. If you thus perform a {{ SomeModel.objects.all() }} in the template (given you of course passed a reference to the model), then it will typically result in an extra database query, but this is not managed by the client. The client does not know what logic the template is calling.
This can make an application more safe as well, since the client has no access to the template itself, and thus can not change the template to obtain sensitive information. Of course by designing specific query input, it can still aim to let the template return sensitive data.
Furthermore the template can contain some logic, that you do not want to share with the clients. By rendering it at the server, the client actually does not see how the HTML was rendered (of course an experienced developer can do some "guesswork" and after a while can have some ideas about how the rendering took place).
But still the "product" of the rendering can result in additional calls
It is however possible that the result will result in extra calls. For example if your result contains <img src="">s, stylesheet links, etc. and other URLs, the browser typically will start fetching these as well. Furthermore if you define JavaScript that performs AJAX calls, these calls result in extra HTTP requests, but those are not done at rendering time of that specific template. These are "independent" calls later that again can result in rendering.
Some technologies render at client side
Note that it does not per se is always that way. Some technologies, like Angular, do (most of) the rendering at the client side. In that case, there is JavaScript code that makes calls to the API, and then "unfolds" the "HTML" as specified by the developer. So it is perfectly possible to make a call to a webservice asking for tweets, and then let some JavaScript "inject" HTML code in the DOM to render the tweets accordingly. The advantage of this is that it makes it easy to change content dynamically (for example update the value of a certain product frequently in the browser).
This however requires that the data that is rendered is available through an API (well an API that can be accesses through HTTP requests), and those calls might need some extra security (for calls asking for data, the credentials usually need to be checked a second time).

Related

Django: Is there any performance differences when using ajax?

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.

How to prevent a Django view that calls an external api from being flooded when it is called by a GET request?

I am writing a Django application with a view that is passed GET parameters. This view contacts an external API to get information, and passes the consolidated information to a template. The external API call is costly and limited. I am concerned that in a production environment, an attacker could write a script to repeatedly load the page with different parameters, (as I'm caching requests, so repeated calls with same parameters are fine), to exhaust my ability to use the external API.
I am trying to ensure that only humans can load my view (or specifically, reach the point of the external API call), or, at least, that a robot can't load it hundreds of times.
The most elegant solution would be some code in the view before the API call that could validate the user somehow. If the user failed the validation, they could be referred to another view or to a different template with a failure message. I am trying to do this as elegantly as possible and not be sloppy, however, so I'm looking for advice on best practice.
Initially, I intuitively wanted to use reCAPTCHA, however, it seems that this is generally used for forms. Adding reCaptcha to the form that directs to this page would not solve my problem, since the attacker could just run the attack by modifying the parameters in the url. Is there a way, either properly or with a hack, to test the user with an invisible, (or possibly visible, but I don't want to deter people by making them fill out a captcha every time), re-captcha in the view? I can't think of a way to do this, but perhaps it's possible.
Hopefully there is some external service or library that I could use to make a simple call to some sort of validator, which at least will block or heavily throttle a user if they are spamming my site, and, at best, would use more sophisticated methods to tell.
The view structure:
def myView(request,query1,query2):
results = call_external_api(query1, query2)
return results to a template using context
Thanks for the help in advance, I hope I was clear in describing my problem!

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)

how to overwrite django template render method handling

In my application, I am sending periodic cron and background task requests to refresh the cache of pages. While sending a force_refresh kwarg from the view is easy, there's no apparent way to send the force_refresh kwarg to methods being accessed from the template. There are plenty of these I'm using, and it would just make things more complex to start calling all these methods from the view.
So I've been trying to overwrite the template render method so that I pass in the force_refresh kwarg whenever a method is being accessed, if the given response is for a background task request.
I realize that it might simply lead to unexpected problems to add this kwarg to all methods being called, and a try/except ArgumentError block wouldn't exactly be a robust solution, if you have any recommendations about a better way to handle this (hopefully besides accessing each of these methods from the view!), it would be useful to hear them.
Sorry, but your use case is precisely what the view function is for.
In the view function you gather all the data. From this you create a dictionary of the latest data which will be used by the template.
All logic goes in the view. The template has minimal processing.

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.