Tải bản đầy đủ - 0 (trang)
Hour 10. Adding Forms to Views

Hour 10. Adding Forms to Views

Tải bản đầy đủ - 0trang

Hour18.CustomizingtheAdmin

Interface

WhatYou'llLearninThisHour

Howtooverrideadmintemplatesatthesitelevel

Howtocreateyourowncustomadminviews

Howtooverrideadmintemplatesattheapplication

level

Howtooverrideadmintemplatesattheobjectlevel

Howtooverrideadmintemplatesattheblocklevel

Howtooverridethebuilt-inadminviews

Theprecedinghourdiscussedhowtocustomizethelookof

modelsintheadmininterface.Thishourdiscusseshowto

customizethelook,feel,andbehavioroftheadmininterface.

TheadmininterfaceismadeupofURLpatternsthatlinkto

viewfunctionsthatrendertemplatefiles.TheURLpatterns,

views,andtemplatesaren'tanydifferentfromwhatyouhave

usedsofar.TheyincludealargeamountofcodeandCSS

formatting,buttheyarestilljustURLpatterns,viewfunctions,

andtemplates.

Theadmintemplatesarestoredinthefollowinglocation

relativetotherootoftheDjangoinstallation:

django/contrib/admin/templates/admin/

TheadminURLpatternsaredefinedinthefollowingURLconf

filerelativetotherootoftheDjangoinstallation:



django/contrib/admin/urls.py



TheadminviewsarelocatedinseveralPythonmodulesinthe

followinglocationrelativetotherootoftheDjangoinstallation:

django/contrib/admin/views/



Thishourdiscussessomeofthewaysyoucanmodifythelook

andfeeloftheadmininterfacebycreatingyourowncustom

admincodetoeitheraddoroverrideexistingadminviews.

BytheWay

Theinformationinthishourisnotmeanttobe

inclusive.Itbarelyscratchesthesurface.Itisdesigned

togiveyousomestartingpointsforcustomizingthe

admininterface.Thereisjustsomuchyoucandoinso

manyways.Thebestdocumentationavailablefor

understandinghowtocustomizetheadmininterfaceis

thecodeitself.



OverridingAdminTemplatesattheSite

Level

Themostcommontypeofcustomizationthatyouwilllikely

wanttoperformintheadmininterfaceistoalterorreplacethe

adminHTMLtemplatefiles.Thiscanpresentaproblem.

IfyoumodifytheadmintemplatesintheDjangoinstallation,

youcustomizetheadmininterface.Theproblemisthatyou

customizetheadmininterfaceforallsitesonthatinstallation,

andifyouupdateDjango,yourcustomizationsareoverwritten.

TheDjangotemplateloaderssolvethisproblem.Ifyouhave



addedadirectorytotheTEMPLATE_DIRSsettinginthesite's

settings.pyfile,thetemplateloaderslooktherefirsttoload

templatefiles.Youcanoverrideanyadmintemplateatthesite

levelbycreatingatemplatethereusingthesamename.

BytheWay

Insteadofcreatingyourowncustomtemplates,youcan

copytheadmintemplatefromtheDjangoinstallationto

yourowntemplateadmindirectoryandthenmakethe

modificationsyouneedtomake.



Forexample,ifyouwantedtooverridethebase_site.html

admintemplate,youcouldjustcreateafilenamed

admin/base_site.htmlinyourtemplatedirectory.

Thefollowingarethemostcommonadmintemplatesthatyou

mightwanttooverride:

admin/base.htmlcontainsmostofthebaseHTMLcodefor

therestoftheadmintemplates.

admin/base_site.htmlextendsthebase.htmlfileand

includesthewindowandbannertitlesforthesite.

admin/login.htmldisplaystheadminloginpage.

admin/index.htmldisplaystheindexpageofmodelsinthe

admininterface.

admin/change_list.htmldisplaysthechangelistfora

model.

admin/change_form.htmldisplaystheaddandupdate

formsforanobjectinamodel.

admin/object_history.htmldisplaysahistoryof



operationsperformedontheobject.

admin/delete_confirmation.htmldisplaysaconfirmation

pagewhendeletinganapplication.



TryItYourself:Overridethebase_site.html



Inthissection,youwilloverridethebase_site.htmltemplatetoaddthe

windowtitleandbannerfortheadmininterface.Followthesestepstomak



1. CreateadirectorycallediFriends/templates/admin.Anyadmintemplat

loadedbeforetheonesintheDjangoinstallation,becauseyouhavealr

toyourTEMPLATE_DIRSsetting.



2. CopythefollowingfilefromtheDjangoinstallationtotheadmindirecto



django/contrib/admin/templates/admin/base_site.html



3. OpentheiFriends/templates/base_site.htmlfileinaneditor.



4. Modifythefollowinglinesofcode,showninListing18.1,toaddtheiFri

titleandbannerintheadmininterface:



{%blocktitle%}{{title|escape}}|{%trans'iFri

{%endblock%}

...

{%trans'iFriendsadministration



5. SavetheiFriends/templates/base_site.htmlfile.

6. GotothefollowingURLinabrowsertoseethechangesshownin



http://127.0.0.1:8000/admin/



Figure18.1.Theadmininterfaceshowingthemodified

titles.

[Viewfullsizeimage]



Thechangesshowuponalladminpagesthatextendthe

base_site.htmltemplate.

Listing18.1.FullContentsofthe

iFriends/templates/base_site.htmlFile

{%extends"admin/base.html"%}

{%loadi18n%}



{%blocktitle%}{{title|escape}}|{%trans'iFriendssitea

{%endblock%}

{%blockbranding%}

{%trans'iFriendsadministration'%}

{%endblock%}

{%blocknav-global%}{%endblock%}



CreatingCustomAdminViews

Anotherwaytocustomizetheadmininterfaceforyourwebsite

istocreateyourowncustomviewstobedisplayedintheadmin

interface.Youcancreateyourowncustomviewfunctionand

templatefileandthenspecifyanadminpathintheURLconffile

whenenablingit.

Creatingcustomviewsfortheadmininterfaceinvolvesthe

samestepsascreatinganormalview.Theviewfunctioncan

liveinanyapplication,andthetemplatefilecanreside

anywhereinthetemplatepath.Theonlyrealdifferencesare

thattheURLtoaccesstheviewbeginswithadmin,andthe

viewfunctionshouldmakecertainthattheuserhasstaff

privilegesbeforeallowinghimorhertoaccesstheview.

WatchOut!

TheadminURLpatternsmatchjustabouteveryURL

pathyoumighttrytouse.SoyouneedtoaddURL

patternsforyourcustomviewsbeforeincludingthe

django.contrib.admin.urlsURLconffileinyourown

URLconffile.

Youcanusethestaff_member_requireddecoratorfunctionto

verifywhethertheuserhasstaffprivilegesbeforegivinghimor

heraccesstotheview:



fromdjango.contrib.admin.views.decoratorsimportstaff_member_

@staff_member_required

defcustom_admin_view(request):

...



TryItYourself:CreateaCustomAdminVie



Inthissection,youwillcreateacustomadminviewfunctionandtemplate

informationabouteachuser'sblogs.YouwilldefineanURLpatternsotha

asanadminURL.Youwillalsoaddthestaff_member_required

onlyuserswithadminprivilegescanaccesstheview.

Followthesestepstocreateandenablethecustomadminview:



1. CreateadirectorycallediFriends/templates/Custominwhichtostore

template.



2. CreateandopenatemplatefilecallediFriends/templates/Custom/

editor.

3. Addthefollowinglinesofcode,showninListing18.2,toextendthe

templateanddefinethetitleblockthatthebase_site.html



{%extends"admin/base_site.html"%}

{%blocktitle%}BlogUsageReport{%endblock%}



4. Addthefullcontentsofthecontentblock,showninListing18.2

5. SavetheiFriends/templates/Custom/blog_usage.htmlfile.

6. OpentheiFriends/Custom/views.pyfileinaneditor.



7. Addthefollowingimportstatements,showninListing18.3.Theywill

render_to_response,Person,RequestContext,andstaff

objectsinthecustomviewfunction:



fromdjango.shortcutsimportrender_to_response



fromiFriends.People.modelsimportPerson

fromdjango.templateimportRequestContext

fromdjango.contrib.admin.views.decoratorsimports



8. Addthefollowingcodethatdefinestheblog_usage()viewfunction,s

generatesalistcontainingtheblogusageforeachPersonobjectinth



defblog_usage(request):

pList=Person.objects.all()

uList=[]

forpinpList:

size=0

forbinp.blogs.all():

size+=b.blog_size()

uList.append({'person':p,

'count':len(p.blogs.all()),

'size':size})



9. Addthefollowingrender_to_response()returnstatementtothe

showninListing18.3.Itrendersthecustomtemplatecreatedinsteps



returnrender_to_response('Custom/blog_usage.html',

{'uList':uList},

context_instance=RequestContext(r



BytheWay



YouneedtoaddRequestContexttotherender_to_resp

theadmintemplateswillhaveaccesstotheUser



10. Addthefollowingdecoratorfunctiontheblog_usage()viewfunction,

ensurethattheuserisloggedinandhasstaffprivileges:



@staff_member_required



11. SavetheiFriends/Custom/views.pyfile.

12. OpentheiFriends/urls.pyfileinaneditor.



13. AddthefollowingURLpattern,beforeyouincludedjango.contrib.ad

blog_usage()functionasanadminURL:



(r'^admin/blog_usage/$','iFriends.Custom.views.blo



14. SavetheiFriends/urls.pyfile.



15. AccessthefollowingURLinabrowsertoverifythattheblog_usage()

showninFigure18.2:



http://127.0.0.1:8000/admin/blog_usage/



Figure18.2.Thecustomblog_usage()functioninth

[Viewfullsizeimage]



Listing18.2.FullContentsofthe

iFriends/templates/Custom/blog_usage.htmlFile

{%extends"admin/base_site.html"%}

{%blocktitle%}BlogUsageReport{%endblock%}

{%blockcontent%}

BlogUsageReport















{%foriteminuList%}











{%endfor%}

PersonBlogCountTotalBytes
{{item.person.name}}{{item.count}}{{item.size}}




Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Hour 10. Adding Forms to Views

Tải bản đầy đủ ngay(0 tr)

×