where do functions that don't display go in django - 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.

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.

Rails: Template is missing / one method for handling POST and GET requests?

I am a Rails newb, and am simply trying to flash an error, on a view with a form. When I sent a POST request to the path of the view I would like to flash the error on, my routes.rb file sends the POST request to my update method in my SchoolApplicationsController. However update is viewless so when I make the POST request to go there, and I meet an error case, I get Template is missing from my Rails Server.
The view where I would like to flash the error is the view which made the request to POST called the pay method in the same controller. What is the common practice here? Do I route the POST for the form submission to the same method as I would do the GET for the pay view, so that any flash errors can be presented in the desired place?
To render a view in a "viewless" action you need to use the render method. In your case render :pay. It will render the form, already filling all the fields, filled previously (if you match the instance variables right).
To flash errors in that form you may use one of several options. First is to simply use flash.now['error'] = 'Whatever error message you need' before you do the rendering. Second is using the .errors method in the instance variable you are updating from the form. Look up the docs or use the console to look up what data that method provides.

Connecting two views in Django

I want to make sure that my visitors (not authenticated users), are unable to visit a particular view without coming directly from a "previous view". I've kind of had to manually create a form preview and confirmation state. It's the step between submission and preview, and preview and confirm I'd like to "secure".
form submission-view -> preview-view -> confirm-view.
Is there some way that I can create a unique hash, POST it, and check if it's correct, or somewhat generate a cookie, session — or anything else that feels clever?
I'm a Django beginner (programming beginner in general) and any snippets' or pointing me in a right direction would be very much appreciated!
Thanks.
There are at least two ways you can accomplish this that I can think of:
One would be to include a hidden field in your form or querystring value that contains your hash/unique that you want to pick up in the next view. If it's not there, or incorrect, redirect.
Another would be to check the referring url from the request.META to see if they've come from the view you want them to come in on first, and save a session value from the form submission to carry through the rest of the views. If it's not there, redirect. If the referring URL isn't what you expect, redirect.
Whether you use a cookie, session, querystring parameter or hidden form post, it's all doing the same thing - validating a value exists. Whatever method works best, is what makes the most sense for you as the developer and most likely maintainer of said app.

Should I use Middleware or write a decorator for this?

I have a situation where a user will be asked to enter their postal code, once they do then they are redirected to the site with content relevant to the postal code they've entered in. There will be categories etc. In a nutshell, the user will see content only relevant to their area.
PLAN --
I want to store their postal code in a cookie and re-use it every time they come back to the site, of course if there is no postal code they should be directed to enter it in a form. The form will be presented before any other content will be.
My questions are should I use a decorator for this and decorate the views with a custom decorator? Or should write middleware? if I write a custom middleware for this should I use process_request process_view, it seems to me process_request gets called on EVERY request, this may pose a problem.
Thanks!
JeffC
If you want to avoid repetition, you'll need to write a middleware. If it's on EVERY page as you say, and the ZIP code is a prerequisite for using the site, then having a middleware call process_request on every request isn't necessarily a bad thing.
On the other hand, is this necessary? Couldn't your URLs just read like: /blah/12345/videos/? Then instead of having to rely on a cookie for a bookmark, your users can just remmber that page. That would negate your having to write a view, as well.
The main question here is how often will you need to use the ZIP code from the cookie. Will it affect the whole site? Or only one part of it?
If the "ZIP-oriented" content will be used only in one part (one or more, but not the whole application), then go for the decorator. It should check for the cookie and if it's not present - redirect to the ZIP selection form. If it's present - continue processing the view in which you will be able to access the ZIP code and use it accordingly.
If the ZIP code is really going to affect the majority of your service and you don't want to decorate every single view - you can go for the middleware. But you are right - it will be called on every request, so be sure it's absolutely necessary.

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)