Part 4:forms and generic views
====> Write a simple form
$ Edit polls\templates\polls\detail.html
<H1>{{Question.question_text}}</H1>{% if error_message%}<P><Strong>{{Error_message}}</Strong></P>{% endif%}<formAction= "{% url ' polls:vote ' question.id%}"Method= "POST">{% Csrf_token%}{% for choice in question.choice_set.all%}<inputtype= "Radio"name= "Choice"ID= "choice{{Forloop.counter}}"value= "{{choice.id}}" /> <label for= "choice{{Forloop.counter}}">{{Choice.choice_text}}</label><BR/>{% endfor%}<inputtype= "Submit"value= "Vote" /></form>
$ Edit polls\views.py
fromDjango.shortcutsImportget_object_or_404, Render fromDjango.httpImportHttpresponseredirect, HttpResponse fromDjango.core.urlresolversImportReverse from. ModelsImportChoice, Question# ...defvote (Request, question_id): P= get_object_or_404 (Question, pk=question_id)Try: Selected_choice= P.choice_set.get (pk=request. post['Choice']) except(Keyerror, choice.doesnotexist):#redisplay the question voting form. returnRender (Request,'polls/detail.html', { 'question': P,'error_message':"You didn ' t select a choice.", }) Else: Selected_choice.votes+ = 1Selected_choice.save ()#Always return a httpresponseredirect after successfully dealing #With POST data. This prevents data from being posted twice if a #user hits the back button. returnHttpresponseredirect (Reverse ('Polls:results', args= (P.id,)))
$ Edit polls\views.py
from Import get_object_or_404, Render def results (Request, question_id): = get_object_or_404 (Question, pk=question_id) return'polls/results.html ', {'question': Question})
$ Edit polls\templates\polls\results.html
<H1>{{Question.question_text}}</H1><ul>{% for choice in question.choice_set.all%}<Li>{{Choice.choice_text}}--{{choice.votes}} vote{{Choice.votes|pluralize}}</Li>{% endfor%}</ul><ahref= "{% url ' polls:detail ' question.id%}">Vote again?</a>
====> Use generic views:less code is better
$ Edit polls\urls.py
fromDjango.conf.urlsImportURL from.ImportViewsurlpatterns=[url (r'^$', views. Indexview.as_view (), name='Index'), url (r'^(? p<pk>[0-9]+)/$', views. Detailview.as_view (), name='Detail'), url (r'^(? p<pk>[0-9]+)/results/$', views. Resultsview.as_view (), name='Results'), url (r'^(? p<question_id>[0-9]+)/vote/$', Views.vote, Name='vote'),]
$ Edit polls\views.py
fromDjango.shortcutsImportget_object_or_404, Render fromDjango.httpImportHttpresponseredirect fromDjango.core.urlresolversImportReverse fromDjango.viewsImportGeneric from. ModelsImportChoice, QuestionclassIndexview (Generic. ListView): Template_name='polls/index.html'Context_object_name='latest_question_list' defGet_queryset (self):"""Return The last five published questions.""" returnQuestion.objects.order_by ('-pub_date') [: 5]classDetailView (Generic. DetailView): Model=Question template_name='polls/detail.html'classResultsview (Generic. DetailView): Model=Question template_name='polls/results.html'defvote (Request, question_id): ...#Same as above
Django Learning Notes (4)