views:

75

answers:

2

I have some links on an html page like , , currently I handle them as so

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

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...

+1  A: 

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.

Dave W. Smith
+1  A: 

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.

Arthur Debert