SlideShare ist ein Scribd-Unternehmen logo
1 von 32
Downloaden Sie, um offline zu lesen
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
staticles 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?

Weitere ähnliche Inhalte

Was ist angesagt?

Jquery presentation
Jquery presentationJquery presentation
Jquery presentation
guest5d87aa6
 
fuser interface-development-using-jquery
fuser interface-development-using-jqueryfuser interface-development-using-jquery
fuser interface-development-using-jquery
Kostas Mavridis
 

Was ist angesagt? (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
 

Andere mochten auch

Django e il Rap Elia Contini
Django e il Rap Elia ContiniDjango e il Rap Elia Contini
Django e il Rap Elia Contini
WEBdeBS
 
Django mongodb -djangoday_
Django mongodb -djangoday_Django mongodb -djangoday_
Django mongodb -djangoday_
WEBdeBS
 

Andere mochten auch (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
 

Ähnlich wie The Django Book, Chapter 16: django.contrib

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
Yared Ayalew
 
Django tutorial 2009
Django tutorial 2009Django tutorial 2009
Django tutorial 2009
Ferenc 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
 
Django Pro ORM
Django Pro ORMDjango Pro ORM
Django Pro ORM
Alex Gaynor
 
Django at Scale
Django at ScaleDjango at Scale
Django at Scale
bretthoerner
 

Ähnlich wie 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
 

KĂźrzlich hochgeladen

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

KĂźrzlich hochgeladen (20)

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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...
 

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 staticles 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
  • 19. But How? • A ContentType model • post_syncdb.connect(update_contenttypes) • GenericForeignKey needs two helping fields • A ForeignKey to ContentType • A eld 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 eld • 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!)