Python Console(3)Vesion Upgrade and Sample Form/Tests/Static/Customize
PythonConsole(3)VesionUpgradeandSampleForm/Tests/Static/Customize
Writeasimpleform
thisisreallyimpressiveabouttheforminthetemplate
{%iferror_message%}
<p><strong>{{error_message}}</strong></p>
{%endif%}
<formaction="{%url'polls:vote'question.id%}"method="post">
{%csrf_token%}
{%forchoiceinquestion.choice_set.all%}
<inputtype="radio"name="choice"id="choice{{forloop.counter}}"value="{{choice.id}}"/>
<labelfor="choice{{forloop.counter}}">{{choice.choice_text}}</label>
<br/>
{%endfor%}
<inputtype="submit"value="Vote"/>
</form>
Actionparttohandletheform
defvote(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):
returnrender(request,'polls/detail.html',{
'question':question,
'error_message':"Youdidn'tselectachoice.",
})
else:
selected_choice.votes+=1selected_choice.save()
returnHttpResponseRedirect(reverse('polls:results',args=(question.id,)))
Setupthenamespaceinurls.py
app_name='polls'
vote{{choice.votes|pluralize}}
willdisplayvotesorvote.Itisvote(s)dependonthechoice.votesnumeric
Usegenericviews:LessCode
…snip…
Automatedtests
Commandtorunthetest
>pythonmanage.pytestpolls
Codesinpolls/tests.pytotesttheDAOlayer
fromdjango.testimportTestCase
importdatetime
fromdjango.utilsimporttimezone
from.modelsimportQuestion
classQuestionMethodTests(TestCase):
deftest_was_published_recently_with_future_question(self):
"""was_published_recently()shouldreturnFalseforquestionswhosepub_dateisinthefuture."”"
time=timezone.now()+datetime.timedelta(days=30)
future_question=Question(pub_date=time)
self.assertIs(future_question.was_published_recently(),False)
TesttheView
classQuestionViewTests(TestCase):
deftest_index_view_with_no_questions(self):
"""Ifnoquestionsexist,anappropriatemessageshouldbedisplayed."""response=self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code,200)
self.assertContains(response,"Nopollsareavailable.")
self.assertQuerysetEqual(response.context['latest_question_list'],[])
deftest_index_view_with_a_past_question(self):
"""Questionswithapub_dateinthepastshouldbedisplayedontheindexpage."""time=timezone.now()+datetime.timedelta(days=-30)
returnQuestion.objects.create(question_text="Pastquestion.",pub_date=time)
response=self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question:Pastquestion.>']
)
deftest_index_view_with_a_future_question(self):
"""Questionswithapub_dateinthefutureshouldnotbedisplayedontheindexpage."""time=timezone.now()+datetime.timedelta(days=30)
returnQuestion.objects.create(question_text="Futurequestion.",pub_date=time)
response=self.client.get(reverse('polls:index'))
self.assertContains(response,"Nopollsareavailable.")
self.assertQuerysetEqual(response.context['latest_question_list'],[])
deftest_index_view_with_future_question_and_past_question(self):
"""Evenifbothpastandfuturequestionsexist,onlypastquestionsshouldbedisplayed."""time=timezone.now()+datetime.timedelta(days=-30)
returnQuestion.objects.create(question_text="Pastquestion.",pub_date=time)
time=timezone.now()+datetime.timedelta(days=30)
returnQuestion.objects.create(question_text="Futurequestion.",pub_date=time)
response=self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question:Pastquestion.>']
)
deftest_index_view_with_two_past_questions(self):
"""Thequestionsindexpagemaydisplaymultiplequestions."""time=timezone.now()+datetime.timedelta(days=-30)
returnQuestion.objects.create(question_text="Pastquestion1.",pub_date=time)
time=timezone.now()+datetime.timedelta(days=-5)
returnQuestion.objects.create(question_text="Pastquestion2.",pub_date=time)
response=self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question:Pastquestion2.>','<Question:Pastquestion1.>']
)
Itisreallygreattohavethesetests.
WaytoloadStaticResource
{%loadstatic%}
<linkrel="stylesheet"type="text/css"href="{%static'polls/style.css'%}"/>
static/polls/style.css
lia{
color:green;
}
LoadImageResource
body{
background:whiteurl("images/background.gif")no-repeatrightbottom;
}
static/polls/images/background.gif
CustomizetheadminForm
Thiswilladjustthepropertiesorderintheview
classQuestionAdmin(admin.ModelAdmin):
fields=['pub_date','question_text']
admin.site.register(Question,QuestionAdmin)
admin.site.register(Choice)
UseFieldSet
classQuestionAdmin(admin.ModelAdmin):
fieldsets=[
(None,{'fields':['question_text']}),
('Dateinformation',{'fields':['pub_date']}),
]
AddchoiceinthequestionPage
classChoiceInline(admin.StackedInline):
model=Choice
extra=3
classQuestionAdmin(admin.ModelAdmin):
fieldsets=[
(None,{'fields':['question_text']}),
('Dateinformation',{'fields':['pub_date']}),
]
inlines=[ChoiceInline]
admin.site.register(Question,QuestionAdmin)
Anotherstyle
classChoiceInline(admin.TabularInline):
CustomizetheAdminList
bydefault,itwilldisplaythestr()oftheobject.
classQuestionAdmin(admin.ModelAdmin):
list_display=('question_text','pub_date','was_published_recently')
fieldsets=[
(None,{'fields':['question_text']}),
('Dateinformation',{'fields':['pub_date']}),
]
list_filter=['pub_date']
inlines=[ChoiceInline]
Inobject,wecanmaketheviewofwas_published_recentlyshorter.
was_published_recently.short_description='Publishedrecently?'
AddsearchTagintheConsolePage
search_fields=['question_text’]
Moredocuments
https://docs.djangoproject.com/en/1.11/topics/
References:
https://docs.djangoproject.com/en/1.11/intro/tutorial04/
https://docs.djangoproject.com/en/1.11/intro/tutorial05/
https://docs.djangoproject.com/en/1.11/intro/tutorial06/
https://docs.djangoproject.com/en/1.11/intro/tutorial07/