I have a problem with django’s MVC. I understand that this is not the traditional MVC, but the documentation emphasizes throughout that it indeed separates presentation from business logic. However, the tutorial comes to a piece of code like this:
def vote(request, poll_id):
p = get_object_or_404(Poll, id=poll_id)
try:
selected_choice = p.choice_set.get(id=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render_to_response('polls/detail.html',
{ 'poll': p, 'error_message': 'You didn''t select a choice.' } )
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('mysite.polls.views.results', args=(p.id,)))
return render_to_response('polls/vote.html', {'poll': p})
(this is maybe not exactly the same as in the tutorial, as it is my implementation, but the concept is the same)
At this part, it handles the request, and (possibly) inserts a record into the database.
Isn’t this wrong? Shouldn’t it be somewhere in the model? What happens in more complex scenarios? Won’t the views get cluttered with lots of db-intensive code, and minimal presentation? Do larger applications have much longer (as in LOC) views?
Nothing is written in stone. In my mind:
That said, because I rather like the philosophy of lean, simple templates; I sometimes have views doing a lot of masticating of the data to make the work of the templates simpler. I don’t think of that as display code, but I’ve had some people telling me that it is.
About your example, you say:
I don’t understand what you mean…
That view is using the model to create a new record. First it asks for the model to update:
Then it modifies the model and saves:
All the logic about saving (including any overriden save() method) is at the model.
You have to have code to handle the actions on the models somewhere. Those are the views. They handle looking up data for display and they handle processing requests for modifications.