Share
Embed
t1.pdf
Lakshman
September 28, 2011
Transcript
78 slides
-
Introduction Paradigms The Admin Interface The Django Advantage Djangoic approach
to implement common web development paradigms Lakshman Prasad April 20, 2011 -
Introduction Paradigms The Admin Interface The Django Advantage • For
building database driven web applications -
Introduction Paradigms The Admin Interface The Django Advantage • For
building database driven web applications • Emphasis on Reuse, DRY and simplicity -
Introduction Paradigms The Admin Interface The Django Advantage About Me
• Active Djangonaut and active in Python world • Part of a few popular open source django applications github.com/becomingGuru. • Co-Authored an ebook ”django-design-patterns” • Architect and develop django applications at InMobi • Earlier, Consulting and Development via Agiliq Solutions • Developed several custom proprietory django applications • twitter.com/becomingGuru http://becomingguru.com -
Introduction Paradigms The Admin Interface The Django Advantage Introduction Definition
About Me Abstractions Paradigms Forms Authentication/Caching/Sessions Inernational/Human/Local ..ization Generic Views Sorting/Pagination/DataBrowse/GRID/Messages/Other The Admin Interface Admin Databrowse The Django Advantage Users Community Endnotes -
Introduction Paradigms The Admin Interface The Django Advantage Use a
Model Form >>> from django . forms import ModelForm # Create the form c l a s s . >>> class ArticleForm ( ModelForm ) : . . . class Meta : . . . model = A r t i c l e # Creating a form to add an a r t i c l e . >>> form = ArticleForm () # Creating a form to change an e x i s t i n g a r t i c l e . >>> a r t i c l e = A r t i c l e . o b j e c t s . get ( pk=1) >>> form = ArticleForm ( i n s t a n c e=a r t i c l e ) -
Introduction Paradigms The Admin Interface The Django Advantage Use Model
Formset from django . forms . models import m o d e l f o r m s e t f a c t o r y AuthorFormSet = m o d e l f o r m s e t f a c t o r y ( Author ) formset = AuthorFormSet () > > > p r i n t formset <i n pu t type=” hidden ” name=”form− TOTAL FORMS” v a l u e=”1” i d=” id form− TOTAL FORMS” /> <i n pu t type=” hidden ” name=”form−INITIAL FORMS” v a l u e=”0” i d=” id form−INITIAL FORMS” /> <i n pu t type=” hidden ” name=”form− MAX NUM FORMS” i d=” id form− MAX NUM FORMS” /> <tr> <th> <l a b e l f o r=” id form −0 −name”>Name:</ l a b e l > </th> <td> <i n pu t i d=” id form −0 −name” type=” t e x t ” name=”form−0 −name” maxlength=”100” /> </td> </tr> -
Introduction Paradigms The Admin Interface The Django Advantage Model Formset
options formset = AuthorFormSet ( qs=Author . o b j e c t s . a l l () , e x t r a =5) formset . i s v a l i d () formset . e r r o r s { ’name ’ : ’ This f i e l d i s r e q u i r e d ’ } formset . changed forms formset . save () -
Introduction Paradigms The Admin Interface The Django Advantage Forms dont
have to save to a Model from django import forms class ContactForm ( forms . Form ) : s u b j e c t = forms . CharField ( max length =100) message = forms . CharField () sender = forms . E mail Fie ld () c c m y s e l f = forms . BooleanField ( r e q u i r e d=False ) def save ( s e l f ) : #Do anything . . . -
Introduction Paradigms The Admin Interface The Django Advantage Form Preview
from django . c o n t r i b . formtools . preview import FormPreview from myapp . models import SomeModel #Add a u r l ( r ’ ˆ post /$ ’ , SomeModelFormPreview ( SomeModelForm )) , #Define form preview class SomeModelFormPreview ( FormPreview ) : def done ( s e l f , request , cleaned data ) : # Do something with the cleaned data , then # r e d i r e c t to a ” s u c c e s s ” page . return HttpResponseRedirect ( ’ /form/ s u c c e s s ’ ) -
Introduction Paradigms The Admin Interface The Django Advantage Form Wizard
class ContactWizard ( FormWizard ) : def done ( s e l f , request , f o r m l i s t ) : do something with the form data ( f o r m l i s t ) return HttpResponseRedirect ( ’ / r e d i r e c t / ’ ) -
Introduction Paradigms The Admin Interface The Django Advantage CSRF Protection
<form a c t i o n=”” method=” post ”>{% c s r f t o k e n %} from django . views . d e c o r a t o r s . c s r f import c s r f p r o t e c t from django . template import RequestContext @ c s r f p r o t e c t def my view ( request ) : c = {} # . . . return r e n d e r t o r e s p o n s e ( ” a template . html” , c , c o n t e x t i n s t a n c e= RequestContext ( request )) -
Introduction Paradigms The Admin Interface The Django Advantage Authentication: Point
to url pattern u r l p a t t e r n s += p a t t e r n s ( ’ django . c o n t r i b . auth . views ’ , u r l ( r ’ ˆ l o g i n /$ ’ , ’ l o g i n ’ ) , u r l ( r ’ ˆ logout /$ ’ , ’ logout ’ ) , u r l ( r ’ ˆ r e g i s t e r /$ ’ , ’ r e g i s t e r ’ ) , u r l ( r ’ ˆ p a s s r e s e t /$ ’ , ’ p a s s w o r d r e s e t ’ ) , u r l ( r ’ ˆ p a s s r e s e t 2 /$ ’ , ’ password reset done ’ ) , u r l ( r ’ ˆ p a s s r e s e t c o n f i r m /(?P<uidb36 >[−\w]+)/ ’ , ’ p a s s w o r d r e s e t c o n f i r m ’ ) , u r l ( r ’ ˆ p as s r e s e t c o m p l e t e /$ ’ , ’ password reset complete ’ ) , ) -
Introduction Paradigms The Admin Interface The Django Advantage Login Required
from django . c o n t r i b . auth . d e c o r a t o r s import \ l o g i n r e q u i r e d @ l o g i n r e q u i r e d ( r e d i r e c t f i e l d n a m e=’ r e d i r e c t t o ’ ) def my view ( request ) : . . . -
Introduction Paradigms The Admin Interface The Django Advantage Authentication backends
class SettingsBackend : ””” Authenticate a g a i n s t the s e t t i n g s ADMIN LOGIN and ADMIN PASSWORD. ””” def a u t h e n t i c a t e ( s e l f , username=None , password=None ) i f l o g i n v a l i d and pwd valid : return user return None def g e t u s e r ( s e l f , u s e r i d ) : try : return User . o b j e c t s . get ( pk=u s e r i d ) except User . DoesNotExist : return None -
Introduction Paradigms The Admin Interface The Django Advantage Open ID
backend c l a s s OpenIdBackend : def a u t h e n t i c a t e ( s e l f , openid key , request , p r o v i d e r , u s e r=None ) : t r y : assoc = U s e r A s s o c i a t i o n . o b j e c t s . get ( openid key=openid key ) return assoc . u s e r except U s e r A s s o c i a t i o n . DoesNotExist : #f e t c h i f openid p r o v i d e r p r o v i d e s any simple r e g i s t r a t i o n f i e l d s i f r e q u e s t . openid and r e q u e s t . openid . s r e g : email = r e q u e s t . openid . s r e g . get ( ’ email ’ ) nickname = r e q u e s t . openid . s r e g . get ( ’ nickname ’ ) firstname , lastname = ( r e q u e s t . openid . s r e g . get ( ’ fullname ’ , ’ ’ ) return u s e r def GooglesAX ( s e l f , o p e n i d r e s p o n s e ) : email = ( o p e n i d r e s p o n s e . ax . g e t S i n g l e ( ’ http :// axschema . org / contact / email ’ )) f i r s t n a m e = ( o p e n i d r e s p o n s e . ax . g e t S i n g l e ( ’ http :// axschema . org /namePerson/ f i r s t ’ )) lastname = ( o p e n i d r e s p o n s e . ax . g e t S i n g l e ( ’ http :// axschema . org /namePerson/ l a s t ’ )) return l o c a l s () def g e t u s e r ( s e l f , u s e r i d ) : t r y : u s e r = User . o b j e c t s . get ( pk=u s e r i d ) return u s e r except User . DoesNotExist : return None -
Introduction Paradigms The Admin Interface The Django Advantage Different blocks
need different caching durations -
Introduction Paradigms The Admin Interface The Django Advantage Generally Memcache
Every page CACHE BACKEND = ’ memcached : / / 1 2 7 . 0 . 0 . 1 : 1 1 2 1 1 / ’ CACHE BACKEND = ’ memcached : //1 72. 19. 26. 240 :11 211 ;\ 172.19.26.242:11212;172.19.26.244:11213/ ’ -
Introduction Paradigms The Admin Interface The Django Advantage Implement a
caching decorator from django . core . cache import cache def c a c h e f o r ( seconds , f e t c h =0): def c a c h e i t ( func ) : def deco func ( s e l f ) : v a l = cache . get ( s e l f . get cache key ( f e t c h )) i f not v a l : v a l = func ( s e l f ) cache . s e t ( s e l f . get cache key ( f e t c h ) , val , seconds ) return v a l return deco func return c a c h e i t -
Introduction Paradigms The Admin Interface The Django Advantage Apply on
the blocks class TwitterBlock ( TwitterSearchBlock ) : template name = ’ t w i t t e r u s e r b l o c k . html ’ a j a x t em p l at e = ’ t w e e t s u s e r . html ’ @cache for (60∗60 , f e t c h =1) def f e t c h d a t a ( s e l f ) : tw = Twitter ( email=’ umoja com ’ ) u s e r t w e e t s = tw . s t a t u s e s . u s e r t i m e l i n e ( screen name=s e l f . data ) return user tweets , None -
Introduction Paradigms The Admin Interface The Django Advantage Different cache
Backends • Database • File System • Local Memory • Redis, a NoSQL store • Dummy- For Development • Sessions can use any of these, or the database. -
Introduction Paradigms The Admin Interface The Django Advantage Humanization and
Localization 19 Apr 2010| naturalday becomes ‘ yesterday ‘ . 20 Apr 2010| naturalday becomes ‘ today ‘ . 1| o r d i n a l becomes ‘1 st ‘ . 2| o r d i n a l becomes ‘2nd ‘ . 1000000| intword becomes ‘1.0 m i l l i o n ‘ . 1200000| intword becomes ‘1.2 m i l l i o n ‘ . {{ value | l o c a l i z e }} -
Introduction Paradigms The Admin Interface The Django Advantage Internationalization {%
b l o c k t r a n s with amount=a r t i c l e . p r i c e %} That w i l l cost $ {{ amount }}. {% endblocktrans %} {% b l o c k t r a n s with myvar=value | f i l t e r %} This w i l l have {{ myvar }} i n s i d e . {% endblocktrans %} class in . forms . I N S t a t e F i e l d class in . forms . INZipCodeField class in . forms . I N S t a t e S e l e c t -
Introduction Paradigms The Admin Interface The Django Advantage Using Generic
Views # some app/ views . py from django . views . g e n e r i c import TemplateView class AboutView ( TemplateView ) : template name = ” about . html” # u r l s . py from django . conf . u r l s . d e f a u l t s import ∗ from some app . views import AboutView u r l p a t t e r n s = p a t t e r n s ( ’ ’ , ( r ’ ˆ about / ’ , AboutView . as view ( ) ) , ) -
Introduction Paradigms The Admin Interface The Django Advantage List and
Object Views from django . views . g e n e r i c import ListView from books . models import Book class AcmeBookListView ( ListView ) : context object name = ” b o o k l i s t ” queryset = Book . o b j e c t s . f i l t e r ( publisher name= ”Acme P u b l i s h i n g ” ) template name = ” books / a c m e l i s t . html” -
Introduction Paradigms The Admin Interface The Django Advantage Mixins from
django import http from django . u t i l s import s i m p l e j s o n as j s o n c l a s s JSONResponseMixin ( o b j e c t ) : def r e n d e r t o r e s p o n s e ( s e l f , context ) : ” Returns a JSON r e sponse c o n t a i n i n g ’ context ’ as payload ” return s e l f . g e t j s o n r e s p o n s e ( s e l f . c o n v e r t c o n t e x t t o j s o n ( context )) def g e t j s o n r e s p o n s e ( s e l f , content , ∗∗ h t t p r e s p o n s e k w a r g s ) : ” Construct an ‘ HttpResponse ‘ o b j e c t . ” return http . HttpResponse ( content , c o n t e n t t y p e=’ a p p l i c a t i o n / j s o n ’ , ∗∗ h t t p r e s p o n s e k w a r g s ) def c o n v e r t c o n t e x t t o j s o n ( s e l f , context ) : ” Convert the context d i c t i o n a r y i n t o a JSON o b j e c t ” return j s o n . dumps ( context ) -
Introduction Paradigms The Admin Interface The Django Advantage Any combinations
of Mixins c l a s s HybridDetailView ( JSONResponseMixin , SingleObjectTemplateResponseMixin , BaseDetailView ) : def r e n d e r t o r e s p o n s e ( s e l f , context ) : # Look f o r a ’ format=j s o n ’ GET argument i f s e l f . r e q u e s t .GET. get ( ’ format ’ , ’ html ’ ) == ’ j s o n ’ : return JSONResponseMixin . r e n d e r t o r e s p o n s e ( s e l f , context ) e l s e : return SingleObjectTemplateResponseMixin . r e n d e r t o r e s p o n s e ( s e l f , context ) -
Introduction Paradigms The Admin Interface The Django Advantage Types of
Generic Views • Simple: Redirect, Render to Template • Detail, List View • Archive View: Date, Month, Year views • Basic CRUD, with or w/o Auth -
Introduction Paradigms The Admin Interface The Django Advantage Builtin support
for Pagination >>> from django . core . paginator import Paginator >>> o b j e c t s = [ ’ john ’ , ’ paul ’ , ’ george ’ , ’ r i n g o ’ ] >>> p = Paginator ( objects , 2) >>> p . count 4 >>> p . num pages 2 >>> p . page range [1 , 2] >>> page1 = p . page (1) >>> page1 <Page 1 of 2> >>> page1 . o b j e c t l i s t [ ’ john ’ , ’ paul ’ ] -
Introduction Paradigms The Admin Interface The Django Advantage Abstract the
pagination in middleware django pagenation {% autopaginate o b j e c t l i s t 10 %} {% paginate %} -
Introduction Paradigms The Admin Interface The Django Advantage Other common
paradigms • Display Image Thumbnail • Store data on a CDN, like Amazon S3 • Periodic tasks with Celery • Decoupled design using Signals • GeoDjango : Framework for all location based applications -
Introduction Paradigms The Admin Interface The Django Advantage Admin Syntax
from django . c o n t r i b import admin from models import Post , Comment class PostAdmin ( admin . ModelAdmin ) : l i s t d i s p l a y = ( ’ t i t l e ’ , ’ datetime ’ ) class CommentAdmin( admin . ModelAdmin ) : l i s t d i s p l a y = ( ’ t e x t ’ ,) admin . s i t e . r e g i s t e r ( Post , PostAdmin ) admin . s i t e . r e g i s t e r (Comment , CommentAdmin) -
Introduction Paradigms The Admin Interface The Django Advantage Databrowse enables
browsable web complete with hyperlinks -
Introduction Paradigms The Admin Interface The Django Advantage Popular Users
• Media • LA Times • NY Times • Washington Post • Guardian • Hindustan TImes -
Introduction Paradigms The Admin Interface The Django Advantage Popular Users
• Media • LA Times • NY Times • Washington Post • Guardian • Hindustan TImes • Web2.0 • Mahalo: 10 million Page views • Many web startups: Convore, Lanyard, Everyblock, GroupQuality, -
Introduction Paradigms The Admin Interface The Django Advantage NASA uses
Django After an extensive trade study, we selected Django ... as the first and primary application environment for the Nebula Cloud. -
Don’t go where the puck is; go where the puck
is going to be -
Introduction Paradigms The Admin Interface The Django Advantage Image Attributions
http ://www. f l i c k r . com/ photos / t e j e d o r o d e l u z /3157690060/ http ://www. f l i c k r . com/ photos /23820645@N05/4287681570/ http ://www. f l i c k r . com/ photos / a i d a n j o n e s /3575000735/ http :// j a c o b i a n . org / http :// s a n j u a n c o l l e g e . edu/ l i b / images / p h i l o s o p h y b r a i n . jpg http ://www. f l i c k r . com/ photos /uhop /105062059/ http :// s3 . amazonaws . com/memebox/ uploads /136/ e x p o n e n t i a l g r a p h 2 . jpg http :// geekandpoke . typepad . com/ geekandpoke / images /2008/06/03/ s e x p l 1 8 . jpg http ://www. f l i c k r . com/ photos /go /253819/ http :// aroundthesphere . f i l e s . wordpress . com/2009/05/ swiss−army−k n i f e . jpg http ://www. f r e e f o t o . com/ images /41/04/41 04 9− − −Keep−Left web . jpg http ://www. f l i c k r . com/ photos / o r i n r o b e r t j o h n /114430223/