Django Learning Notes (4)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.