SlideShare una empresa de Scribd logo
1 de 32
Descargar para leer sin conexión
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?

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Destacado

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
 

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

Similar 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
 

Similar 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

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 

Último (20)

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 

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