Whenever you create a form that alters data server-side, use method="post". This tip is good Web development practice.
you should always return an HttpResponseRedirect
after successfully dealing with POST data. This tip isn’t specific to Django; it’s just good Web development practice.
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
HttpResponseRedirect returns a 301 or 302 response code to the browser, instead of more common 200 (ok), or 404 (not found). That simply instructs the browser to load the given URL. The interesting part is that that given URL replaces the original (POST) one in the browser's history.