SlideShare a Scribd company logo
1 of 33
Download to read offline
Django admin
Python meetup
Ines Jelovac
Zagreb, 14 June 2016
Django Web Framework
● High-level Python Web framework
● MVC
Django admin
● Automatic interface
● For site administrators
● Reads model metadata
● Customizing:
○ Layout
○ Filters
○ Actions
Model example
class Article(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL)
title = models.CharField(max_length=200)
lead_text = models.CharField(max_length=300)
content = models.TextField()
publish_date = models.DateTimeField()
image = models.ImageField()
section = models.ManyToManyField(Section)
def __str__(self):
return self.title
Model metadata
class Article(models.Model):
...
class Meta:
verbose_name = _('Article')
verbose_name_plural = _('Articles')
ordering = ('-publish_date',)
Default admin interface
app/admin.py
from django.contrib import admin
from articles.models import Article
admin.site.register(Article)
Default list interface
Customizing objects list: list_display
● List objects page
○ Default: str() of each object
● list_display option
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
list_display = ['title', 'publish_date']
● list_display_links option
Customizing objects list: list_display
Customizing objects list: empty_value_display
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
list_display = ['title', 'publish_date']
empty_value_display = '(unknown)'
Customizing objects list: empty_value_display
Customizing objects list: list_filter
● Model field
● Foreign key attribute lookup
● Custom querysets
● preserve_filters option
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
list_display = ['title', 'publish_date']
empty_value_display = '(unknown)'
list_filter = ['section', PublishedListFilter]
Customizing objects list: list_filter
class PublishedListFilter(admin.SimpleListFilter):
title = 'published'
parameter_name = 'publish_date'
def lookups(self, request, model_admin):
return (
('published', 'published'),
('not_published', 'not published')
)
def queryset(self, request, queryset):
if self.value() == 'published':
return queryset.filter(publish_date__isnull=False)
if self.value() == 'not_published':
return queryset.filter(publish_date__isnull=True)
Customizing objects list: list_filter
Customizing objects list: date_hierarchy
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
list_display = ['title', 'publish_date']
empty_value_display = '(unknown)'
list_filter = ['section', PublishedListFilter]
date_hierarchy = 'publish_date'
Customizing objects list: date_hierarchy
Customizing objects list: search_fields
● Model field
● Foreign key attribute lookup
● Operators
○ ^ to match starting at the beginning of the field
○ = for case-insensitive exact matching
○ @ operator to perform a full text match
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
list_display = ['title', 'publish_date']
empty_value_display = '(unknown)'
list_filter = ['section', PublishedListFilter]
date_hierarchy = 'publish_date'
search_fields = ['title']
Customizing objects list: search_fields
Customizing objects list: list_editable
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
list_display = ['title', 'lead_text','publish_date']
empty_value_display = '(unknown)'
list_filter = ['section', PublishedListFilter]
date_hierarchy = 'publish_date'
search_fields = ['title']
list_editable = ['lead_text']
Customizing objects list: list_editable
Default edit interface
Default edit interface
● Default buttons
○ Delete
○ Save and add another
○ Save and continue editing
○ Save
● save_as option: if set to True “Save as new” replaces “Save and add
another” button
Customizing edit interface: fields
● fields option
○ List of fields in model edit form
○ Change order
○ Group in same line
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
fields = [
'author',
('title', 'lead_text'),
'content',
('publish_date', 'image'),
'section'
]
Customizing edit interface
Customizing edit interface
● exclude option
○ List of fields not shown in edit form
● readonly_fields option
○ Field or method
● fieldsets option
○ Group fields
● form option
○ Replace default Form with custom
● view_on_site option
○ Boolean - calls get_absolute_url
○ Callable
Customizing edit interface: many to many
● filter_horizontal option
● filter_vertical option
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
…
filter_horizontal = ['section']
Customizing edit interface: filter_horizontal
Customizing edit interface: inlines
● TabularInline
● StackedInline
class GalleryInline(admin.TabularInline):
model = GalleyImage
extra = 2
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
...
filter_horizontal = ['section']
inlines = [GalleryInline]
Customizing edit interface: inlines
Customizing admin interface: actions
● Functions that get called with a list of objects selected on the change list page
● Simple logic: use function
● Complex logic: redirect the user to another view in function
def delete_publish_date(modeladmin, request, queryset):
queryset.update(publish_date=None)
delete_publish_date.short_description = "Delete published
date for selected articles"
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
…
actions = [delete_publish_date]
Customizing edit interface: actions
Customizing admin interface: actions
Optimization
● show_full_result_count option in list view
○ Eliminates expensive count
● list_select_related option in list view
○ Django will use select_related in query
● raw_id_fields option in edit view
There is more
● Overriding default templates
● Overriding methods
● History view
● Decorator @staff_member_required
ljudski_potencijali@styria.hr

More Related Content

What's hot

What's hot (12)

Drupal 9 training ajax
Drupal 9 training ajaxDrupal 9 training ajax
Drupal 9 training ajax
 
11. delete record
11. delete record11. delete record
11. delete record
 
10. view one record
10. view one record10. view one record
10. view one record
 
12. edit record
12. edit record12. edit record
12. edit record
 
Session 2 django material for training at baabtra models
Session 2 django material for training at baabtra modelsSession 2 django material for training at baabtra models
Session 2 django material for training at baabtra models
 
Two scoopsofdjango ch16 dealing with the user model
Two scoopsofdjango ch16   dealing with the user modelTwo scoopsofdjango ch16   dealing with the user model
Two scoopsofdjango ch16 dealing with the user model
 
8. vederea inregistrarilor
8. vederea inregistrarilor8. vederea inregistrarilor
8. vederea inregistrarilor
 
Window object methods (timer related)
Window object methods (timer related)Window object methods (timer related)
Window object methods (timer related)
 
Forms, Getting Your Money's Worth
Forms, Getting Your Money's WorthForms, Getting Your Money's Worth
Forms, Getting Your Money's Worth
 
Validation
ValidationValidation
Validation
 
20. CodeIgniter edit images
20. CodeIgniter edit images20. CodeIgniter edit images
20. CodeIgniter edit images
 
Two scoopsofdjango common patterns for forms
Two scoopsofdjango   common patterns for formsTwo scoopsofdjango   common patterns for forms
Two scoopsofdjango common patterns for forms
 

Viewers also liked

Magic Methods (Python meetup)
Magic Methods (Python meetup)Magic Methods (Python meetup)
Magic Methods (Python meetup)Ines Jelovac
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Eric Palakovich Carr
 
Starters with Django
Starters with Django Starters with Django
Starters with Django BeDjango
 
Efficient Django
Efficient DjangoEfficient Django
Efficient DjangoDavid Arcos
 
David Threets Professional Persona Project
David Threets Professional Persona Project David Threets Professional Persona Project
David Threets Professional Persona Project David Threet
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial之宇 趙
 
Getting Started With Django
Getting Started With DjangoGetting Started With Django
Getting Started With Djangojeff_croft
 
Django 實戰 - 自己的購物網站自己做
Django 實戰 - 自己的購物網站自己做Django 實戰 - 自己的購物網站自己做
Django 實戰 - 自己的購物網站自己做flywindy
 
那些年,我用 Django Admin 接的案子
那些年,我用 Django Admin 接的案子那些年,我用 Django Admin 接的案子
那些年,我用 Django Admin 接的案子flywindy
 
Django로 배우는 쉽고 빠른 웹개발 study 자료
Django로 배우는 쉽고 빠른 웹개발 study 자료Django로 배우는 쉽고 빠른 웹개발 study 자료
Django로 배우는 쉽고 빠른 웹개발 study 자료Han Sung Kim
 
Architecture at SimpleGeo: Staying Agile at Scale
Architecture at SimpleGeo: Staying Agile at ScaleArchitecture at SimpleGeo: Staying Agile at Scale
Architecture at SimpleGeo: Staying Agile at ScaleMike Malone
 
The Web map stack on Django
The Web map stack on DjangoThe Web map stack on Django
The Web map stack on DjangoPaul Smith
 
Open edX vs Moodle
Open edX vs MoodleOpen edX vs Moodle
Open edX vs MoodleBeDjango
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for BeginnersJason Davies
 
DJango admin interface
DJango admin interfaceDJango admin interface
DJango admin interfaceMahesh Shitole
 

Viewers also liked (20)

Magic Methods (Python meetup)
Magic Methods (Python meetup)Magic Methods (Python meetup)
Magic Methods (Python meetup)
 
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
 
Starters with Django
Starters with Django Starters with Django
Starters with Django
 
Efficient Django
Efficient DjangoEfficient Django
Efficient Django
 
David Threets Professional Persona Project
David Threets Professional Persona Project David Threets Professional Persona Project
David Threets Professional Persona Project
 
Free django
Free djangoFree django
Free django
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial
 
Getting Started With Django
Getting Started With DjangoGetting Started With Django
Getting Started With Django
 
Django 實戰 - 自己的購物網站自己做
Django 實戰 - 自己的購物網站自己做Django 實戰 - 自己的購物網站自己做
Django 實戰 - 自己的購物網站自己做
 
那些年,我用 Django Admin 接的案子
那些年,我用 Django Admin 接的案子那些年,我用 Django Admin 接的案子
那些年,我用 Django Admin 接的案子
 
Django로 배우는 쉽고 빠른 웹개발 study 자료
Django로 배우는 쉽고 빠른 웹개발 study 자료Django로 배우는 쉽고 빠른 웹개발 study 자료
Django로 배우는 쉽고 빠른 웹개발 study 자료
 
Architecture at SimpleGeo: Staying Agile at Scale
Architecture at SimpleGeo: Staying Agile at ScaleArchitecture at SimpleGeo: Staying Agile at Scale
Architecture at SimpleGeo: Staying Agile at Scale
 
The Web map stack on Django
The Web map stack on DjangoThe Web map stack on Django
The Web map stack on Django
 
Advanced Django
Advanced DjangoAdvanced Django
Advanced Django
 
Django in the Real World
Django in the Real WorldDjango in the Real World
Django in the Real World
 
Open edX vs Moodle
Open edX vs MoodleOpen edX vs Moodle
Open edX vs Moodle
 
Scaling Django
Scaling DjangoScaling Django
Scaling Django
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for Beginners
 
DJango admin interface
DJango admin interfaceDJango admin interface
DJango admin interface
 
Django Best Practices
Django Best PracticesDjango Best Practices
Django Best Practices
 

Similar to Django Admin (Python meeutp)

날로 먹는 Django admin 활용
날로 먹는 Django admin 활용날로 먹는 Django admin 활용
날로 먹는 Django admin 활용KyeongMook "Kay" Cha
 
Django Admin: Widgetry & Witchery
Django Admin: Widgetry & WitcheryDjango Admin: Widgetry & Witchery
Django Admin: Widgetry & WitcheryPamela Fox
 
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
 
Symfony Admin Generator - generator.yml
Symfony Admin Generator - generator.ymlSymfony Admin Generator - generator.yml
Symfony Admin Generator - generator.ymlRavi Mone
 
Python Development (MongoSF)
Python Development (MongoSF)Python Development (MongoSF)
Python Development (MongoSF)Mike Dirolf
 
What’S New In Newforms Admin
What’S New In Newforms AdminWhat’S New In Newforms Admin
What’S New In Newforms AdminDjangoCon2008
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJoaquim Rocha
 
DjangoGirls Seoul | Django Study: Django Model-View-Template
DjangoGirls Seoul | Django Study: Django Model-View-TemplateDjangoGirls Seoul | Django Study: Django Model-View-Template
DjangoGirls Seoul | Django Study: Django Model-View-TemplateJunbum Lee
 
Odoo Experience 2018 - Inherit from These 10 Mixins to Empower Your App
Odoo Experience 2018 - Inherit from These 10 Mixins to Empower Your AppOdoo Experience 2018 - Inherit from These 10 Mixins to Empower Your App
Odoo Experience 2018 - Inherit from These 10 Mixins to Empower Your AppElínAnna Jónasdóttir
 
The Django Book, Chapter 16: django.contrib
The Django Book, Chapter 16: django.contribThe Django Book, Chapter 16: django.contrib
The Django Book, Chapter 16: django.contribTzu-ping Chung
 
XPages Workshop: Concepts And Exercises
XPages Workshop:   Concepts And ExercisesXPages Workshop:   Concepts And Exercises
XPages Workshop: Concepts And Exercisesddrschiw
 
Django tutorial 2009
Django tutorial 2009Django tutorial 2009
Django tutorial 2009Ferenc Szalai
 
Configuration Entities in Drupal 8
Configuration Entities in Drupal 8Configuration Entities in Drupal 8
Configuration Entities in Drupal 8Eugene Kulishov
 
Odoo Experience 2018 - From a Web Controller to a Full CMS
Odoo Experience 2018 - From a Web Controller to a Full CMSOdoo Experience 2018 - From a Web Controller to a Full CMS
Odoo Experience 2018 - From a Web Controller to a Full CMSElínAnna Jónasdóttir
 
An in Depth Journey into Odoo's ORM
An in Depth Journey into Odoo's ORMAn in Depth Journey into Odoo's ORM
An in Depth Journey into Odoo's ORMOdoo
 

Similar to Django Admin (Python meeutp) (20)

날로 먹는 Django admin 활용
날로 먹는 Django admin 활용날로 먹는 Django admin 활용
날로 먹는 Django admin 활용
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Django Admin: Widgetry & Witchery
Django Admin: Widgetry & WitcheryDjango Admin: Widgetry & Witchery
Django Admin: Widgetry & Witchery
 
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
 
Symfony Admin Generator - generator.yml
Symfony Admin Generator - generator.ymlSymfony Admin Generator - generator.yml
Symfony Admin Generator - generator.yml
 
Python Development (MongoSF)
Python Development (MongoSF)Python Development (MongoSF)
Python Development (MongoSF)
 
What’S New In Newforms Admin
What’S New In Newforms AdminWhat’S New In Newforms Admin
What’S New In Newforms Admin
 
Django Heresies
Django HeresiesDjango Heresies
Django Heresies
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
DjangoGirls Seoul | Django Study: Django Model-View-Template
DjangoGirls Seoul | Django Study: Django Model-View-TemplateDjangoGirls Seoul | Django Study: Django Model-View-Template
DjangoGirls Seoul | Django Study: Django Model-View-Template
 
Odoo Experience 2018 - Inherit from These 10 Mixins to Empower Your App
Odoo Experience 2018 - Inherit from These 10 Mixins to Empower Your AppOdoo Experience 2018 - Inherit from These 10 Mixins to Empower Your App
Odoo Experience 2018 - Inherit from These 10 Mixins to Empower Your App
 
The Django Book, Chapter 16: django.contrib
The Django Book, Chapter 16: django.contribThe Django Book, Chapter 16: django.contrib
The Django Book, Chapter 16: django.contrib
 
Django
DjangoDjango
Django
 
XPages Workshop: Concepts And Exercises
XPages Workshop:   Concepts And ExercisesXPages Workshop:   Concepts And Exercises
XPages Workshop: Concepts And Exercises
 
Django tutorial 2009
Django tutorial 2009Django tutorial 2009
Django tutorial 2009
 
Django design-patterns
Django design-patternsDjango design-patterns
Django design-patterns
 
Discovering Django - zekeLabs
Discovering Django - zekeLabsDiscovering Django - zekeLabs
Discovering Django - zekeLabs
 
Configuration Entities in Drupal 8
Configuration Entities in Drupal 8Configuration Entities in Drupal 8
Configuration Entities in Drupal 8
 
Odoo Experience 2018 - From a Web Controller to a Full CMS
Odoo Experience 2018 - From a Web Controller to a Full CMSOdoo Experience 2018 - From a Web Controller to a Full CMS
Odoo Experience 2018 - From a Web Controller to a Full CMS
 
An in Depth Journey into Odoo's ORM
An in Depth Journey into Odoo's ORMAn in Depth Journey into Odoo's ORM
An in Depth Journey into Odoo's ORM
 

Recently uploaded

(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?Paolo Missier
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptxFIDO Alliance
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Hiroshi SHIBATA
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxFIDO Alliance
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxFIDO Alliance
 
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...marcuskenyatta275
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxFIDO Alliance
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxFIDO Alliance
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024Lorenzo Miniero
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...FIDO Alliance
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data SciencePaolo Missier
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctBrainSell Technologies
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingScyllaDB
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGDSC PJATK
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfalexjohnson7307
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024Stephen Perrenod
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...ScyllaDB
 

Recently uploaded (20)

(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage Intacct
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdf
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
 

Django Admin (Python meeutp)

  • 1. Django admin Python meetup Ines Jelovac Zagreb, 14 June 2016
  • 2. Django Web Framework ● High-level Python Web framework ● MVC Django admin ● Automatic interface ● For site administrators ● Reads model metadata ● Customizing: ○ Layout ○ Filters ○ Actions
  • 3. Model example class Article(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL) title = models.CharField(max_length=200) lead_text = models.CharField(max_length=300) content = models.TextField() publish_date = models.DateTimeField() image = models.ImageField() section = models.ManyToManyField(Section) def __str__(self): return self.title
  • 4. Model metadata class Article(models.Model): ... class Meta: verbose_name = _('Article') verbose_name_plural = _('Articles') ordering = ('-publish_date',)
  • 5. Default admin interface app/admin.py from django.contrib import admin from articles.models import Article admin.site.register(Article)
  • 7. Customizing objects list: list_display ● List objects page ○ Default: str() of each object ● list_display option @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): list_display = ['title', 'publish_date'] ● list_display_links option
  • 9. Customizing objects list: empty_value_display @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): list_display = ['title', 'publish_date'] empty_value_display = '(unknown)'
  • 10. Customizing objects list: empty_value_display
  • 11. Customizing objects list: list_filter ● Model field ● Foreign key attribute lookup ● Custom querysets ● preserve_filters option @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): list_display = ['title', 'publish_date'] empty_value_display = '(unknown)' list_filter = ['section', PublishedListFilter]
  • 12. Customizing objects list: list_filter class PublishedListFilter(admin.SimpleListFilter): title = 'published' parameter_name = 'publish_date' def lookups(self, request, model_admin): return ( ('published', 'published'), ('not_published', 'not published') ) def queryset(self, request, queryset): if self.value() == 'published': return queryset.filter(publish_date__isnull=False) if self.value() == 'not_published': return queryset.filter(publish_date__isnull=True)
  • 14. Customizing objects list: date_hierarchy @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): list_display = ['title', 'publish_date'] empty_value_display = '(unknown)' list_filter = ['section', PublishedListFilter] date_hierarchy = 'publish_date'
  • 15. Customizing objects list: date_hierarchy
  • 16. Customizing objects list: search_fields ● Model field ● Foreign key attribute lookup ● Operators ○ ^ to match starting at the beginning of the field ○ = for case-insensitive exact matching ○ @ operator to perform a full text match @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): list_display = ['title', 'publish_date'] empty_value_display = '(unknown)' list_filter = ['section', PublishedListFilter] date_hierarchy = 'publish_date' search_fields = ['title']
  • 17. Customizing objects list: search_fields
  • 18. Customizing objects list: list_editable @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): list_display = ['title', 'lead_text','publish_date'] empty_value_display = '(unknown)' list_filter = ['section', PublishedListFilter] date_hierarchy = 'publish_date' search_fields = ['title'] list_editable = ['lead_text']
  • 19. Customizing objects list: list_editable
  • 21. Default edit interface ● Default buttons ○ Delete ○ Save and add another ○ Save and continue editing ○ Save ● save_as option: if set to True “Save as new” replaces “Save and add another” button
  • 22. Customizing edit interface: fields ● fields option ○ List of fields in model edit form ○ Change order ○ Group in same line @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): fields = [ 'author', ('title', 'lead_text'), 'content', ('publish_date', 'image'), 'section' ]
  • 24. Customizing edit interface ● exclude option ○ List of fields not shown in edit form ● readonly_fields option ○ Field or method ● fieldsets option ○ Group fields ● form option ○ Replace default Form with custom ● view_on_site option ○ Boolean - calls get_absolute_url ○ Callable
  • 25. Customizing edit interface: many to many ● filter_horizontal option ● filter_vertical option @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): … filter_horizontal = ['section']
  • 26. Customizing edit interface: filter_horizontal
  • 27. Customizing edit interface: inlines ● TabularInline ● StackedInline class GalleryInline(admin.TabularInline): model = GalleyImage extra = 2 @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): ... filter_horizontal = ['section'] inlines = [GalleryInline]
  • 29. Customizing admin interface: actions ● Functions that get called with a list of objects selected on the change list page ● Simple logic: use function ● Complex logic: redirect the user to another view in function def delete_publish_date(modeladmin, request, queryset): queryset.update(publish_date=None) delete_publish_date.short_description = "Delete published date for selected articles" @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): … actions = [delete_publish_date]
  • 30. Customizing edit interface: actions Customizing admin interface: actions
  • 31. Optimization ● show_full_result_count option in list view ○ Eliminates expensive count ● list_select_related option in list view ○ Django will use select_related in query ● raw_id_fields option in edit view
  • 32. There is more ● Overriding default templates ● Overriding methods ● History view ● Decorator @staff_member_required