Where functions that are not displayed go to django

I have some links on html page like, currently I am processing them like this

<p> <a href="/cases/{{case.id}}/case_rate/-">rate down</a>

      

and enter url.py:

 (r'^cases/(?P<case_id>\d+)/case_rate/(?P<oper>.)$', 'mysite.cases.views.case_rate'),

      

then I have a view function that processes the logic and gets into the DB and then does the following:

return HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))

      

Do I have a better way to do this? I can see how good it will be because he needs to redraw the screen to show the new rating ...

0


a source to share


2 answers


The typical way to handle this is an ajax request.

Instead of a link, you put a javascript handler that calls the view, which updates the db, and returns a json / xml object with the new rating for the element. Then another javascript handle gets that response and updates the screen rating number without reloading the page.



Ideally, you keep both versions: plain html (the one you currently have) and ajax. Ajax can be bound to an element after the page has loaded, so if javascript is not available, you will still have a working site.

Then, in terms of organization, you can have an "ajax" parameter on your view. The view should update the db accordingly, and if it is an ajax call, return a json / xml response, otherwise return a new page. This way you can keep the logic (object fetch, db update) in one place.

+1


a source


If you are asking if case_rate should still go to views.py given that it returns a redirect rather than providing content, the answer is yes, since case_rate processes the request and returns a response.



But consider a situation where you had two view functions in views.py that had some duplicate code in it, and you decided to include that duplicate code in another function that did not execute the request or return a response. Would it be fair play to leave in views.py? Of course, if moving elsewhere will make the code harder to read. Or you can choose it elsewhere. This is truly your appeal based on your sense of taste.

+1


a source







All Articles