SlideShare uma empresa Scribd logo
1 de 32
Baixar para ler offline
django.contrib
2013-09-02. Django Workshop.
About me
• TP (@uranusjr)
• RTFD
• Find me anywhere
django.contrib
• Utilities
• Optional
• Don’t (need to) re-invent the wheels
• These serves as examples if you want!
• May change in the future
django.contrib
• Utilities
• Optional
• Don’t (need to) re-invent the wheels
• These serves as examples if you want!
• May change in the future
Major changes Since 1.3
Packages
Major changesMajor changes
Packages
Since Notes
auth 1.5 Custom user model; get_profile() deprecated
formtools 1.4 Reimplemented with CBVs
staticfiles 1.4 New {%  static  %} template tag
localflavor 1.5 Deprecated
markup 1.5 Deprecated
django.contrib
• Site-building tools
• Auth & auth, sessions, etc.
• Utilities
• Page generation, messaging, etc.
• Black magic
django.contrib
• Site-building tools
• Auth & auth, sessions, etc.
• Utilities
• Page generation, messaging, etc.
• Black magic
Previously, on TDB...
• admin (Chapter 6)
• sitemaps, syndication (Chapter 13)
• auth, sessions (Chapter 14)
CSRF Protection
• CSRF: Cross-Site Request Forgery
• Prevention
• Use POST for state-changing processes
• Add a token to every POST form
• Only allow POST when the form has an
appropriate token value
django.contrib.csrf
• Depends on django.contrib.sessions
• Template tag {%  csrf_token  %}
• Middleware CsrfMiddleware
• Beware of its limitations!
• AJAX contents
• Don’t use @csrf_exempt unless needed
django.contrib.sites
• Sharing a data base between multiple sites
• Site:A name and a domain
• A SITE_ID in settings.py
• The Site model
• Site.objects.get_current()
• The CurrentSiteManager
Content-Serving
• django.contrib.flatpages
• Reuse templates for “static” web pages
without redundant views
• django.contrib.redirects
• Manage redirections in the database
• django.contrib.admindocs
Cool Thingz
• django.contrib.formtools
• Split Django form into multiple pages
• django.contrib.gis
• GeoDjango
• django.contrib.humanize
• django.contrib.webdesign
Questions?
Django’s void  *
• Django’s relations require concrete targets
• Multi-table subclassing is costly
• A “pointer to anything”
It’s Possible
• Python uses duck-typing already
• Magic built-in: getattribute
• Django’s get_model
• Django relations are just ids
ContentTypes
• GenericForeignKey
• GenericRelation
• Forms and formsets
• Admin inlines
But How?
• A ContentType model
• post_syncdb.connect(update_contenttypes)
• GenericForeignKey needs two helping fields
• A ForeignKey to ContentType
• A field to hold the primary key (usually a
PositiveIntegerField)
from  django.db  import  models
from  django.contrib.contenttypes  import  generic
class  Attachment(models.Model):
        attached_file  =  models.FileField(...)
        content_type  =  models.ForeignKey(
                'contenttypes.ContentType'
        )
        object_id  =  models.PositiveIntegerField()
        content_object  =  generic.GenericForeignKey(
                'content_type',  'object_id'
        )
        #  ...  blah  blah  blah  ...
from  django.db  import  models
from  django.contrib.contenttypes  import  generic
class  Attachment(models.Model):
        attached_file  =  models.FileField(...)
        content_type  =  models.ForeignKey(
                'contenttypes.ContentType'
        )
        object_id  =  models.PositiveIntegerField()
        content_object  =  generic.GenericForeignKey(
                'content_type',  'object_id'
        )
        #  ...  blah  blah  blah  ...
from  django.db  import  models
from  django.contrib.contenttypes  import  generic
class  Attachment(models.Model):
        attached_file  =  models.FileField(...)
        content_type  =  models.ForeignKey(
                'contenttypes.ContentType'
        )
        object_id  =  models.PositiveIntegerField()
        content_object  =  generic.GenericForeignKey(
                'content_type',  'object_id'
        )
        #  ...  blah  blah  blah  ...
from  django.db  import  models
from  django.contrib.contenttypes  import  generic
class  Attachment(models.Model):
        attached_file  =  models.FileField(...)
        content_type  =  models.ForeignKey(
                'contenttypes.ContentType'
        )
        object_id  =  models.PositiveIntegerField()
        content_object  =  generic.GenericForeignKey()
        #  ...  blah  blah  blah  ...
post_attachments  =  Attachment.objects.filter(
        content_object=BlogPost.objects.latest('id')
)
taget_user  =  User.objects.get(username='uranusjr')
message  =  Message.objects.filter(
        from_user=request.user,  to_user=taget_user
).latest('created_at')
message_attachment  =  Attachment.objects.filter(
        content_object=message
)
message_attachment.content_object  =  ...
message_attachment.save()
Caveats
• Not really a database field
• Cannot filter (or exclude, get, etc.)
• Cannot aggregate
• Some annotations do work
• No automatic reverse
from  django.db  import  models
from  django.contrib.contenttypes  import  generic
class  BlogPost(models.Model):
        #  ...  blah  blah  blah  ...
        attachments  =  generic.GenericRelation(Attachment)
        #  ...  blah  blah  blah  ...
from  django.db  import  models
from  django.contrib.contenttypes  import  generic
class  BlogPost(models.Model):
        #  ...  blah  blah  blah  ...
        attachments  =  generic.GenericRelation(Attachment)
        #  ...  blah  blah  blah  ...
blog_post  =  BlogPost.objects.latest('id')
#  These  two  become  equivalent
Attachment.objects.filter(content_object=blog_post)
blog_post.attachments
Applications
• django.contrib.comments
• django-ratings
• Post tagging
• “Like”
django.contrib
• Utilities
• Optional
• Don’t (need to) re-invent the wheels
• If you have to, these serves as examples
• May change in the future
django.contrib
• Site-building tools
• Auth & auth, sessions, etc.
• Utilities
• Page generation, messaging, etc.
• Black magic
django.contrib
• Site-building tools
• Auth & auth, sessions, etc.
• Utilities
• Page generation, messaging, etc.
• Black magic
• Hacks (in a good way!)
Questions?

Mais conteúdo relacionado

Mais procurados

Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptDonald Sipe
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of JavascriptTarek Yehia
 
Template rendering in rails
Template rendering in rails Template rendering in rails
Template rendering in rails Hung Wu Lo
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentationguest5d87aa6
 
The Django Book Chapter 9 - Django Workshop - Taipei.py
The Django Book Chapter 9 - Django Workshop - Taipei.pyThe Django Book Chapter 9 - Django Workshop - Taipei.py
The Django Book Chapter 9 - Django Workshop - Taipei.pyTzu-ping Chung
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJoaquim Rocha
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoMohamed Mosaad
 
Educate 2017: Customizing Authoring: How our APIs let you create powerful sol...
Educate 2017: Customizing Authoring: How our APIs let you create powerful sol...Educate 2017: Customizing Authoring: How our APIs let you create powerful sol...
Educate 2017: Customizing Authoring: How our APIs let you create powerful sol...Learnosity
 
Lab#1 - Front End Development
Lab#1 - Front End DevelopmentLab#1 - Front End Development
Lab#1 - Front End DevelopmentWalid Ashraf
 
fuser interface-development-using-jquery
fuser interface-development-using-jqueryfuser interface-development-using-jquery
fuser interface-development-using-jqueryKostas Mavridis
 
Javascript Object Oriented Programming
Javascript Object Oriented ProgrammingJavascript Object Oriented Programming
Javascript Object Oriented ProgrammingBunlong Van
 

Mais procurados (16)

Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Jquery library
Jquery libraryJquery library
Jquery library
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Template rendering in rails
Template rendering in rails Template rendering in rails
Template rendering in rails
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentation
 
The Django Book Chapter 9 - Django Workshop - Taipei.py
The Django Book Chapter 9 - Django Workshop - Taipei.pyThe Django Book Chapter 9 - Django Workshop - Taipei.py
The Django Book Chapter 9 - Django Workshop - Taipei.py
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup Cairo
 
Educate 2017: Customizing Authoring: How our APIs let you create powerful sol...
Educate 2017: Customizing Authoring: How our APIs let you create powerful sol...Educate 2017: Customizing Authoring: How our APIs let you create powerful sol...
Educate 2017: Customizing Authoring: How our APIs let you create powerful sol...
 
Lab#1 - Front End Development
Lab#1 - Front End DevelopmentLab#1 - Front End Development
Lab#1 - Front End Development
 
Metaprogramming in ES6
Metaprogramming in ES6Metaprogramming in ES6
Metaprogramming in ES6
 
fuser interface-development-using-jquery
fuser interface-development-using-jqueryfuser interface-development-using-jquery
fuser interface-development-using-jquery
 
Javascript Object Oriented Programming
Javascript Object Oriented ProgrammingJavascript Object Oriented Programming
Javascript Object Oriented Programming
 

Destaque

Django e il Rap Elia Contini
Django e il Rap Elia ContiniDjango e il Rap Elia Contini
Django e il Rap Elia ContiniWEBdeBS
 
Django - The Web framework for perfectionists with deadlines
Django - The Web framework for perfectionists with deadlinesDjango - The Web framework for perfectionists with deadlines
Django - The Web framework for perfectionists with deadlinesMarkus Zapke-Gründemann
 
Django - The Web framework for perfectionists with deadlines
Django - The Web framework  for perfectionists with deadlinesDjango - The Web framework  for perfectionists with deadlines
Django - The Web framework for perfectionists with deadlinesMarkus Zapke-Gründemann
 
Rabbitmq & Postgresql
Rabbitmq & PostgresqlRabbitmq & Postgresql
Rabbitmq & PostgresqlLucio Grenzi
 
Django mongodb -djangoday_
Django mongodb -djangoday_Django mongodb -djangoday_
Django mongodb -djangoday_WEBdeBS
 
2007 - 应用系统脆弱性概论
2007 - 应用系统脆弱性概论 2007 - 应用系统脆弱性概论
2007 - 应用系统脆弱性概论 Na Lee
 
2016 py con2016_lightingtalk_php to python
2016 py con2016_lightingtalk_php to python2016 py con2016_lightingtalk_php to python
2016 py con2016_lightingtalk_php to pythonJiho Lee
 
Authentication & Authorization in ASPdotNet MVC
Authentication & Authorization in ASPdotNet MVCAuthentication & Authorization in ASPdotNet MVC
Authentication & Authorization in ASPdotNet MVCMindfire Solutions
 
NoSql Day - Apertura
NoSql Day - AperturaNoSql Day - Apertura
NoSql Day - AperturaWEBdeBS
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1Ke Wei Louis
 
NoSql Day - Chiusura
NoSql Day - ChiusuraNoSql Day - Chiusura
NoSql Day - ChiusuraWEBdeBS
 

Destaque (20)

Django-Queryset
Django-QuerysetDjango-Queryset
Django-Queryset
 
Django e il Rap Elia Contini
Django e il Rap Elia ContiniDjango e il Rap Elia Contini
Django e il Rap Elia Contini
 
Website optimization
Website optimizationWebsite optimization
Website optimization
 
Html5 History-API
Html5 History-APIHtml5 History-API
Html5 History-API
 
Django - The Web framework for perfectionists with deadlines
Django - The Web framework for perfectionists with deadlinesDjango - The Web framework for perfectionists with deadlines
Django - The Web framework for perfectionists with deadlines
 
Load testing
Load testingLoad testing
Load testing
 
Django - The Web framework for perfectionists with deadlines
Django - The Web framework  for perfectionists with deadlinesDjango - The Web framework  for perfectionists with deadlines
Django - The Web framework for perfectionists with deadlines
 
Rabbitmq & Postgresql
Rabbitmq & PostgresqlRabbitmq & Postgresql
Rabbitmq & Postgresql
 
Vim for Mere Mortals
Vim for Mere MortalsVim for Mere Mortals
Vim for Mere Mortals
 
Django mongodb -djangoday_
Django mongodb -djangoday_Django mongodb -djangoday_
Django mongodb -djangoday_
 
Bottle - Python Web Microframework
Bottle - Python Web MicroframeworkBottle - Python Web Microframework
Bottle - Python Web Microframework
 
2007 - 应用系统脆弱性概论
2007 - 应用系统脆弱性概论 2007 - 应用系统脆弱性概论
2007 - 应用系统脆弱性概论
 
2016 py con2016_lightingtalk_php to python
2016 py con2016_lightingtalk_php to python2016 py con2016_lightingtalk_php to python
2016 py con2016_lightingtalk_php to python
 
Digesting jQuery
Digesting jQueryDigesting jQuery
Digesting jQuery
 
Authentication & Authorization in ASPdotNet MVC
Authentication & Authorization in ASPdotNet MVCAuthentication & Authorization in ASPdotNet MVC
Authentication & Authorization in ASPdotNet MVC
 
EuroDjangoCon 2009 - Ein Rückblick
EuroDjangoCon 2009 - Ein RückblickEuroDjangoCon 2009 - Ein Rückblick
EuroDjangoCon 2009 - Ein Rückblick
 
PyClab.__init__(self)
PyClab.__init__(self)PyClab.__init__(self)
PyClab.__init__(self)
 
NoSql Day - Apertura
NoSql Day - AperturaNoSql Day - Apertura
NoSql Day - Apertura
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1
 
NoSql Day - Chiusura
NoSql Day - ChiusuraNoSql Day - Chiusura
NoSql Day - Chiusura
 

Semelhante a The Django Book, Chapter 16: django.contrib

Introduction Django
Introduction DjangoIntroduction Django
Introduction DjangoWade Austin
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics PresentationShrinath Shenoy
 
Django Overview
Django OverviewDjango Overview
Django OverviewBrian Tol
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineYared Ayalew
 
Django tutorial 2009
Django tutorial 2009Django tutorial 2009
Django tutorial 2009Ferenc Szalai
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Jacob Kaplan-Moss
 
Mezzanine簡介 (at) Taichung.py
Mezzanine簡介 (at) Taichung.pyMezzanine簡介 (at) Taichung.py
Mezzanine簡介 (at) Taichung.pyMax Lai
 
Django workshop : let's make a blog
Django workshop : let's make a blogDjango workshop : let's make a blog
Django workshop : let's make a blogPierre Sudron
 
Why I liked Mezzanine CMS
Why I liked Mezzanine CMSWhy I liked Mezzanine CMS
Why I liked Mezzanine CMSRenyi Khor
 
Data Migrations in the App Engine Datastore
Data Migrations in the App Engine DatastoreData Migrations in the App Engine Datastore
Data Migrations in the App Engine DatastoreRyan Morlok
 
國民雲端架構 Django + GAE
國民雲端架構 Django + GAE國民雲端架構 Django + GAE
國民雲端架構 Django + GAEWinston Chen
 
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]Udit Gangwani
 
The Time for Vanilla Web Components has Arrived
The Time for Vanilla Web Components has ArrivedThe Time for Vanilla Web Components has Arrived
The Time for Vanilla Web Components has ArrivedGil Fink
 
You've done the Django Tutorial, what next?
You've done the Django Tutorial, what next?You've done the Django Tutorial, what next?
You've done the Django Tutorial, what next?Andy McKay
 
Python Development (MongoSF)
Python Development (MongoSF)Python Development (MongoSF)
Python Development (MongoSF)Mike Dirolf
 

Semelhante a The Django Book, Chapter 16: django.contrib (20)

Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
 
Django Overview
Django OverviewDjango Overview
Django Overview
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App Engine
 
templates in Django material : Training available at Baabtra
templates in Django material : Training available at Baabtratemplates in Django material : Training available at Baabtra
templates in Django material : Training available at Baabtra
 
Django tutorial 2009
Django tutorial 2009Django tutorial 2009
Django tutorial 2009
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)
 
Mezzanine簡介 (at) Taichung.py
Mezzanine簡介 (at) Taichung.pyMezzanine簡介 (at) Taichung.py
Mezzanine簡介 (at) Taichung.py
 
Django workshop : let's make a blog
Django workshop : let's make a blogDjango workshop : let's make a blog
Django workshop : let's make a blog
 
Why I liked Mezzanine CMS
Why I liked Mezzanine CMSWhy I liked Mezzanine CMS
Why I liked Mezzanine CMS
 
Data Migrations in the App Engine Datastore
Data Migrations in the App Engine DatastoreData Migrations in the App Engine Datastore
Data Migrations in the App Engine Datastore
 
Tango with django
Tango with djangoTango with django
Tango with django
 
國民雲端架構 Django + GAE
國民雲端架構 Django + GAE國民雲端架構 Django + GAE
國民雲端架構 Django + GAE
 
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Django Pro ORM
Django Pro ORMDjango Pro ORM
Django Pro ORM
 
The Time for Vanilla Web Components has Arrived
The Time for Vanilla Web Components has ArrivedThe Time for Vanilla Web Components has Arrived
The Time for Vanilla Web Components has Arrived
 
You've done the Django Tutorial, what next?
You've done the Django Tutorial, what next?You've done the Django Tutorial, what next?
You've done the Django Tutorial, what next?
 
Python Development (MongoSF)
Python Development (MongoSF)Python Development (MongoSF)
Python Development (MongoSF)
 
Django at Scale
Django at ScaleDjango at Scale
Django at Scale
 

Último

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 

Último (20)

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

The Django Book, Chapter 16: django.contrib

  • 2. About me • TP (@uranusjr) • RTFD • Find me anywhere
  • 3. django.contrib • Utilities • Optional • Don’t (need to) re-invent the wheels • These serves as examples if you want! • May change in the future
  • 4. django.contrib • Utilities • Optional • Don’t (need to) re-invent the wheels • These serves as examples if you want! • May change in the future
  • 5. Major changes Since 1.3 Packages Major changesMajor changes Packages Since Notes auth 1.5 Custom user model; get_profile() deprecated formtools 1.4 Reimplemented with CBVs staticfiles 1.4 New {%  static  %} template tag localflavor 1.5 Deprecated markup 1.5 Deprecated
  • 6. django.contrib • Site-building tools • Auth & auth, sessions, etc. • Utilities • Page generation, messaging, etc. • Black magic
  • 7. django.contrib • Site-building tools • Auth & auth, sessions, etc. • Utilities • Page generation, messaging, etc. • Black magic
  • 8. Previously, on TDB... • admin (Chapter 6) • sitemaps, syndication (Chapter 13) • auth, sessions (Chapter 14)
  • 9. CSRF Protection • CSRF: Cross-Site Request Forgery • Prevention • Use POST for state-changing processes • Add a token to every POST form • Only allow POST when the form has an appropriate token value
  • 10. django.contrib.csrf • Depends on django.contrib.sessions • Template tag {%  csrf_token  %} • Middleware CsrfMiddleware • Beware of its limitations! • AJAX contents • Don’t use @csrf_exempt unless needed
  • 11. django.contrib.sites • Sharing a data base between multiple sites • Site:A name and a domain • A SITE_ID in settings.py • The Site model • Site.objects.get_current() • The CurrentSiteManager
  • 12. Content-Serving • django.contrib.flatpages • Reuse templates for “static” web pages without redundant views • django.contrib.redirects • Manage redirections in the database • django.contrib.admindocs
  • 13. Cool Thingz • django.contrib.formtools • Split Django form into multiple pages • django.contrib.gis • GeoDjango • django.contrib.humanize • django.contrib.webdesign
  • 15.
  • 16. Django’s void  * • Django’s relations require concrete targets • Multi-table subclassing is costly • A “pointer to anything”
  • 17. It’s Possible • Python uses duck-typing already • Magic built-in: getattribute • Django’s get_model • Django relations are just ids
  • 18. ContentTypes • GenericForeignKey • GenericRelation • Forms and formsets • Admin inlines
  • 19. But How? • A ContentType model • post_syncdb.connect(update_contenttypes) • GenericForeignKey needs two helping fields • A ForeignKey to ContentType • A field to hold the primary key (usually a PositiveIntegerField)
  • 20. from  django.db  import  models from  django.contrib.contenttypes  import  generic class  Attachment(models.Model):        attached_file  =  models.FileField(...)        content_type  =  models.ForeignKey(                'contenttypes.ContentType'        )        object_id  =  models.PositiveIntegerField()        content_object  =  generic.GenericForeignKey(                'content_type',  'object_id'        )        #  ...  blah  blah  blah  ...
  • 21. from  django.db  import  models from  django.contrib.contenttypes  import  generic class  Attachment(models.Model):        attached_file  =  models.FileField(...)        content_type  =  models.ForeignKey(                'contenttypes.ContentType'        )        object_id  =  models.PositiveIntegerField()        content_object  =  generic.GenericForeignKey(                'content_type',  'object_id'        )        #  ...  blah  blah  blah  ...
  • 22. from  django.db  import  models from  django.contrib.contenttypes  import  generic class  Attachment(models.Model):        attached_file  =  models.FileField(...)        content_type  =  models.ForeignKey(                'contenttypes.ContentType'        )        object_id  =  models.PositiveIntegerField()        content_object  =  generic.GenericForeignKey(                'content_type',  'object_id'        )        #  ...  blah  blah  blah  ...
  • 23. from  django.db  import  models from  django.contrib.contenttypes  import  generic class  Attachment(models.Model):        attached_file  =  models.FileField(...)        content_type  =  models.ForeignKey(                'contenttypes.ContentType'        )        object_id  =  models.PositiveIntegerField()        content_object  =  generic.GenericForeignKey()        #  ...  blah  blah  blah  ...
  • 24. post_attachments  =  Attachment.objects.filter(        content_object=BlogPost.objects.latest('id') ) taget_user  =  User.objects.get(username='uranusjr') message  =  Message.objects.filter(        from_user=request.user,  to_user=taget_user ).latest('created_at') message_attachment  =  Attachment.objects.filter(        content_object=message ) message_attachment.content_object  =  ... message_attachment.save()
  • 25. Caveats • Not really a database field • Cannot filter (or exclude, get, etc.) • Cannot aggregate • Some annotations do work • No automatic reverse
  • 26. from  django.db  import  models from  django.contrib.contenttypes  import  generic class  BlogPost(models.Model):        #  ...  blah  blah  blah  ...        attachments  =  generic.GenericRelation(Attachment)        #  ...  blah  blah  blah  ...
  • 27. from  django.db  import  models from  django.contrib.contenttypes  import  generic class  BlogPost(models.Model):        #  ...  blah  blah  blah  ...        attachments  =  generic.GenericRelation(Attachment)        #  ...  blah  blah  blah  ... blog_post  =  BlogPost.objects.latest('id') #  These  two  become  equivalent Attachment.objects.filter(content_object=blog_post) blog_post.attachments
  • 29. django.contrib • Utilities • Optional • Don’t (need to) re-invent the wheels • If you have to, these serves as examples • May change in the future
  • 30. django.contrib • Site-building tools • Auth & auth, sessions, etc. • Utilities • Page generation, messaging, etc. • Black magic
  • 31. django.contrib • Site-building tools • Auth & auth, sessions, etc. • Utilities • Page generation, messaging, etc. • Black magic • Hacks (in a good way!)