SlideShare a Scribd company logo
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?

More Related Content

What's hot

Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Iván Fernández Perea
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
Donald Sipe
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
Tarek 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.py
Tzu-ping Chung
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
Joaquim 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 Cairo
Mohamed 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 Development
Walid Ashraf
 
Metaprogramming in ES6
Metaprogramming in ES6Metaprogramming in ES6
Metaprogramming in ES6
Héctor Pablos López
 
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 Programming
Bunlong Van
 

What's hot (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
 

Viewers also liked

Django-Queryset
Django-QuerysetDjango-Queryset
Django-Queryset
Mindfire Solutions
 
Django e il Rap Elia Contini
Django e il Rap Elia ContiniDjango e il Rap Elia Contini
Django e il Rap Elia ContiniWEBdeBS
 
Website optimization
Website optimizationWebsite optimization
Website optimization
Mindfire Solutions
 
Html5 History-API
Html5 History-APIHtml5 History-API
Html5 History-API
Mindfire Solutions
 
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
Markus Zapke-Gründemann
 
Load testing
Load testingLoad testing
Load testing
Mindfire Solutions
 
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
Markus Zapke-Gründemann
 
Rabbitmq & Postgresql
Rabbitmq & PostgresqlRabbitmq & Postgresql
Rabbitmq & Postgresql
Lucio Grenzi
 
Vim for Mere Mortals
Vim for Mere MortalsVim for Mere Mortals
Vim for Mere Mortals
Clayton Parker
 
Django mongodb -djangoday_
Django mongodb -djangoday_Django mongodb -djangoday_
Django mongodb -djangoday_WEBdeBS
 
Bottle - Python Web Microframework
Bottle - Python Web MicroframeworkBottle - Python Web Microframework
Bottle - Python Web Microframework
Markus Zapke-Gründemann
 
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 python
Jiho Lee
 
Digesting jQuery
Digesting jQueryDigesting jQuery
Digesting jQuery
Mindfire Solutions
 
Authentication & Authorization in ASPdotNet MVC
Authentication & Authorization in ASPdotNet MVCAuthentication & Authorization in ASPdotNet MVC
Authentication & Authorization in ASPdotNet MVC
Mindfire Solutions
 
PyClab.__init__(self)
PyClab.__init__(self)PyClab.__init__(self)
PyClab.__init__(self)
Tzu-ping Chung
 
NoSql Day - Apertura
NoSql Day - AperturaNoSql Day - Apertura
NoSql Day - Apertura
WEBdeBS
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1
Ke Wei Louis
 
NoSql Day - Chiusura
NoSql Day - ChiusuraNoSql Day - Chiusura
NoSql Day - Chiusura
WEBdeBS
 

Viewers also liked (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 to The Django Book, Chapter 16: django.contrib

Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
Wade Austin
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
Shrinath Shenoy
 
Django Overview
Django OverviewDjango Overview
Django Overview
Brian 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
 
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
baabtra.com - No. 1 supplier of quality freshers
 
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.py
Max 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 blog
Pierre Sudron
 
Why I liked Mezzanine CMS
Why I liked Mezzanine CMSWhy I liked Mezzanine CMS
Why I liked Mezzanine CMS
Renyi 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 Datastore
Ryan Morlok
 
Tango with django
Tango with djangoTango with django
Tango with django
Rajan Kumar Upadhyay
 
國民雲端架構 Django + GAE
國民雲端架構 Django + GAE國民雲端架構 Django + GAE
國民雲端架構 Django + GAE
Winston 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 Arrived
Gil 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 to 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
 

Recently uploaded

Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 

Recently uploaded (20)

Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 

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