SlideShare une entreprise Scribd logo
1  sur  32
Télécharger pour lire hors ligne
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?

Contenu connexe

Tendances

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
 

Tendances (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
 

En vedette

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
 

En vedette (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
 

Similaire à 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
 

Similaire à 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
 

Dernier

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 

Dernier (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

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!)