SlideShare a Scribd company logo
Chapter 6:The Django Admin Site
⽑毛⽑毛
Admin interface
• A Web-based interface
• Limited to trusted site administrators
• Enable the adding, editing and deletion of site content
• Some common examples
• The interface you use to post to your blog
• The backend site managers use to moderate user-
generated comments
The django.contrib packages
• Contain various useful add-ons to the core framework
• You can think of django.contrib as Django’s equivalent of the
Python standard library
• Django’s automatic admin is part of django.contrib
• Other available features
• A user authentication system (django.contrib.auth)
• Anonymous sessions (django.contrib.sessions)
• A system for user comments (django.contrib.comments)
Activating the Admin Interface
• The Django admin site is entirely optional
• That means you’ll need to take a few steps to activate it in your project
• First, make a few changes to your settings file
• Add 'django.contrib.admin' to the INSTALLED_APPS setting
• The order of INSTALLED_APPS doesn’t matter
• Make sure INSTALLED_APPS contains 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.messages' and
‘django.contrib.sessions'
• Make sure MIDDLEWARE_CLASSES contains
'django.middleware.common.CommonMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware' and
'django.contrib.auth.middleware.AuthenticationMiddleware'
Activating the Admin Interface
• Second, run python manage.py syncdb
• Install the extra database tables that the admin interface uses
• The first time you run syncdb, you’ll be asked about creating a superuser
• To be able to log in to the admin site
• If you don’t do this, you’ll need to run python manage.py createsuperuser
separately
• Third, add the admin site to your URLconf
!
!
Using the Admin Site
• Run the development server
• python manage.py runserver
• Visit http://127.0.0.1:8000/admin/ in your Web browser
!
!
!
!
Using the Admin Site
• Log in with the username and password you set up when you added your
superuser
• Once you’re logged in, the first thing you’ll see will be the admin home page
• List all the available types of data that can be edited
• The two default admin-editable models are only Groups and Users
!
!
!
!
Other languages
• If your Web browser is configured to prefer a language other than
English
• Add 'django.middleware.locale.LocaleMiddleware' to your
MIDDLEWARE_CLASSES setting
• Make sure it appears after
‘django.contrib.sessions.middleware.SessionMiddleware'
• Reload the admin index page
• If a translation for your language is available, you will see the
change
• Django ships with translations for dozens of languages
Using the Admin Site
• Click the “Change” link in the “Users” row to load the change list page for users
• This page displays all users in the database
• There are useful filtering, sorting and searching options
• Filtering options are at right, sorting is available by clicking a column
header, and the search box at the top lets you search by username
!
!
!
!
Using the Admin Site
• Click the username of the user you created, and you’ll see the edit form for that user
• This page lets you change the attributes of the user, like the first/last names and various
permissions
• To change a user’s password, you should click “change password form” under the
password field rather than editing the hashed code
• You can delete a record by clicking the delete button at the bottom left of its edit form
• You can add a record by clicking “Add” in the appropriate column of the admin home page
• Admin interface also handles input validation
!
!
Using the Admin Site
• When you edit an existing object, you’ll notice a History link in the
upper-right corner of the window
• Every change made through the admin interface is logged, and
you can examine this log by clicking the History link
!
!
!
!
Adding Your Models to the Admin Site
• Add our own models to the admin site, so we can add, change and delete objects
in our custom database tables using this nice interface
• Continue the books example from Chapter 5, where we defined three models:
Publisher, Author and Book
• Within the books directory (mysite/books), create a file called admin.py
!
!
!
!
• This code tells the Django admin site to offer an interface for each of these
models
Adding Your Models to the Admin Site
• The admin site can handle foreign keys and many-to-many relationships
!
!
!
!
!
• The publisher (a ForeignKey) is represented by a select box
• The authors field (a ManyToManyField) is represented by a multiple-select box
• Both fields sit next to a green plus sign icon that lets you add related records of
that type
Making Fields Optional
• By default, all fields have blank=False, which means blank
values are not allowed
• Make email field optional
• Add blank=True to the email field
!
!
• On the Admin Site, you’ll notice the field’s label – “Email”
– is no longer bolded
Making Fields Optional
• Make date and numeric fields optional
• Use both null=True and blank=True
!
!
!
• Adding null=True is more complicated than adding blank=True, because null=True
changes the semantics of the database
• To complete this change, we’ll need to update the database
• Django does not attempt to automate changes to database schemas, so it’s your own
responsibility to execute the appropriate ALTER TABLE statement
• Use manage.py dbshell to enter your database server’s shell.
Customizing Field Labels
• On the admin site’s edit forms, each field’s label is generated from its model field name
• Django just replaces underscores with spaces and capitalizes the first character
• The Book model’s publication_date field has the label “Publication date”
• However, field names don’t always lend themselves to nice admin field labels, so in some cases
you might want to customize a label
• By specifying verbose_name in the appropriate model field
!
!
!
• Note that you shouldn’t capitalize the first letter of a verbose_name unless it should always be
capitalized
• Django will automatically capitalize it when it needs to
Custom ModelAdmin classes
• The Django admin site offers a wealth of options that let you customize how the admin
site works for a particular model
• Such options live in ModelAdmin classes
• Customizing change lists
• By default, the change list displays the result of __unicode__() for each object
• In Chapter 5, we defined the __unicode__() method for Author objects to display
the first name and last name together
!
!
!
Custom ModelAdmin classes
• We can improve on this default behavior by adding a few other fields to the change list
display
• To see each author’s e-mail address in this list, and it’d be nice to be able to sort by
first and last name
• To make this happen, we’ll define a ModelAdmin class for the Author model
• This class is the key to customizing the admin
• Edit admin.py to make these changes
!
!
!
Custom ModelAdmin classes
• Create the class AuthorAdmin, which subclasses ModelAdmin, holds custom configuration for
a specific admin model
• One customization – list_display, which is set to a tuple of field names to display on the change
list page.
• These field names must exist in the model
• Altere the admin.site.register(). You can read this as: “Register the Author model with the
AuthorAdmin options.”
!
!
!
!
Custom ModelAdmin classes
• Next, let’s add a simple search bar
• Add search_fields to the AuthorAdmin
!
!
• Reload the page in your browser, and you should see a search bar at the top
• Search against the first_name and last_name fields
• Is case-insensitive and searches both fields
• Search for the string "bar" would find both an author with the first name Barney and an
author with the last name Hobarson
!
Custom ModelAdmin classes
• Next, let’s add some date filters to our Book model’s
change list page
!
!
!
!
Custom ModelAdmin classes
• list_filter, which is set to a tuple of fields to use to create filters along the right side of the
change list page
• Django provides shortcuts to filter the list to “Today,” “Past 7 days,” “This month” and
“This year”
!
!
!
!
!
• list_filter also works on fields of other types, not just DateField
• As long as there are at least 2 values to choose from
Custom ModelAdmin classes
• Another way to offer date filters is to use the date_hierarchy admin option
• The change list page gets a date drill-down navigation bar at the top of the list
• It starts with a list of available years, then drills down into months and individual days
• Note that date_hierarchy takes a string, not a tuple, because only one date field can be
used to make the hierarchy
!
!
!
!
!
Custom ModelAdmin classes
• let’s change the default ordering so that books on the change list page are always
ordered descending by their publication date
• By default, the change list orders objects according to their model’s ordering
within class Meta
• ordering - Just pass a list or tuple of field names, and add a minus sign to a
field to use descending sort order
!
!
!
!
Custom ModelAdmin classes
• Customizing edit forms
• First, let’s customize the way fields are ordered
• By default, the order of fields in an edit form corresponds to the order
they’re defined in the model
• Use the fields option in our ModelAdmin subclass
!
!
!
• After this change, the edit form for books will use the given ordering for
fields
Custom ModelAdmin classes
• Another useful thing the fields option lets you do is to exclude certain fields from
being edited entirely
• Just leave out the field(s) you want to exclude
• You might use this if your admin users are only trusted to edit a certain segment
of your data
• For example, in our book database, we could hide the publication_date field from
being editable
!
!
!
Custom ModelAdmin classes
• As a result, the edit form for books doesn’t offer a way to specify
the publication date
• When a user uses this incomplete form to add a new book, Django
will simply set the publication_date to None
• Make sure that field has null=True
!
!
!
Custom ModelAdmin classes
• Customization for many-to-many fields
• The admin site represents each ManyToManyField as a multiple-select boxes
• Multiple-select boxes can be difficult to use
• The admin site’s solution is filter_horizontal
!
!
!
!
Custom ModelAdmin classes
!
!
!
!
!
• Highly recommend using filter_horizontal for any ManyToManyField that has more than 10
items
• ModelAdmin classes also support a filter_vertical option
• This works exactly as filter_horizontal, but the resulting JavaScript interface stacks the two
boxes vertically instead of horizontally
• filter_horizontal and filter_vertical only work on ManyToManyField fields, not ForeignKey fields
Custom ModelAdmin classes
• Sometimes you don’t want to incur the overhead of having to select all the related objects to
display in the drop-down
• For example, if our book database grows to include thousands of publishers, the “Add
book” form could take a while to load, because it would have to load every publisher for
display in the <select> box
• The way to fix this is to use an option called raw_id_fields
!
!
!
!
!
Users, Groups, and Permissions
• If you’re logged in as a superuser, you have access to create, edit, and delete any object
• Naturally, different environments require different permission systems
• Django’s admin site uses a permissions system
• You can edit users and permissions through the admin interface just like any other object
• There’s a set of three boolean flags
• The “active” flag controls whether the user is active at all
• If this flag is off and the user tries to log in, he won’t be allowed in, even with a valid
password
• The “staff” flag controls whether the user is allowed to log in to the admin interface
• This flag differentiates between public users and administrators
• The “superuser” flag gives the user full access to add, create and delete any item in the
admin interface
Users, Groups, and Permissions
• Each object editable through the admin interface has three permissions: a
create permission, an edit permission and a delete permission
• When you create a user, that user has no permissions, and it’s up to you to give
the user specific permissions
• These permissions are defined per-model, not per-object
• So they let you say “John can make changes to any book,” but they don’t let
you say “John can make changes to any book published by Apress.”
• You can also assign users to groups
• A group is simply a set of permissions to apply to all members of that
group
• Groups are useful for granting identical permissions to a subset of users
When and Why to Use the Admin
Interface – And When Not to
• Django’s admin site especially shines when nontechnical users need to be able to
enter data
• Django’s admin interface is facilitating the simultaneous work of content producers
and programmers
• Beyond these obvious data entry tasks, the admin site is useful in a few other cases
• Inspecting data models
• Managing acquired data
• Quick and dirty data-management apps
• The admin site is not intended to be a public interface to data, nor is it intended to
allow for sophisticated sorting and searching of your data
• It is for trusted site administrators
Thanks for listening

More Related Content

What's hot

Final year project presentation
Final year project presentationFinal year project presentation
Final year project presentation
Noman Manzoor
 
Java Method, Static Block
Java Method, Static BlockJava Method, Static Block
Java Method, Static Block
Infoviaan Technologies
 
Ppt full stack developer
Ppt full stack developerPpt full stack developer
Ppt full stack developer
SudhirVarpe1
 
Java Basics
Java BasicsJava Basics
Java Basics
Brandon Black
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
Lovely Professional University
 
Srs (Software Requirement Specification Document)
Srs (Software Requirement Specification Document) Srs (Software Requirement Specification Document)
Srs (Software Requirement Specification Document)
Fatima Qayyum
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
Hitesh Kumar
 
online-shopping-documentation-srs for TYBSCIT sem 6
 online-shopping-documentation-srs for TYBSCIT sem 6 online-shopping-documentation-srs for TYBSCIT sem 6
online-shopping-documentation-srs for TYBSCIT sem 6
YogeshDhamke2
 
Java package
Java packageJava package
Java package
CS_GDRCST
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
Nilesh Dalvi
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
Hitesh Kumar
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)Arjun Shanka
 
Basic Crud In Django
Basic Crud In DjangoBasic Crud In Django
Basic Crud In Django
mcantelon
 
Method overriding
Method overridingMethod overriding
Method overriding
Azaz Maverick
 
Cloud computing
Cloud computingCloud computing
Cloud computing
Dr. B T Sampath Kumar
 
Java applet
Java appletJava applet
Java applet
Rohan Gajre
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
RahulAnanda1
 
3 java - variable type
3  java - variable type3  java - variable type
3 java - variable type
vinay arora
 
Canteen Food Management System
Canteen Food Management SystemCanteen Food Management System
Canteen Food Management System
Shubham Dhage
 

What's hot (20)

Final year project presentation
Final year project presentationFinal year project presentation
Final year project presentation
 
Java Method, Static Block
Java Method, Static BlockJava Method, Static Block
Java Method, Static Block
 
Ppt full stack developer
Ppt full stack developerPpt full stack developer
Ppt full stack developer
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
Srs (Software Requirement Specification Document)
Srs (Software Requirement Specification Document) Srs (Software Requirement Specification Document)
Srs (Software Requirement Specification Document)
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
online-shopping-documentation-srs for TYBSCIT sem 6
 online-shopping-documentation-srs for TYBSCIT sem 6 online-shopping-documentation-srs for TYBSCIT sem 6
online-shopping-documentation-srs for TYBSCIT sem 6
 
Java package
Java packageJava package
Java package
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Basic Crud In Django
Basic Crud In DjangoBasic Crud In Django
Basic Crud In Django
 
Method overriding
Method overridingMethod overriding
Method overriding
 
Cloud computing
Cloud computingCloud computing
Cloud computing
 
Java applet
Java appletJava applet
Java applet
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
3 java - variable type
3  java - variable type3  java - variable type
3 java - variable type
 
Canteen Food Management System
Canteen Food Management SystemCanteen Food Management System
Canteen Food Management System
 

Viewers also liked

Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
Richard Leland
 
REALIDAD AUMENTADA
REALIDAD AUMENTADAREALIDAD AUMENTADA
REALIDAD AUMENTADAcvilmar
 
ALR resume Sept 2015
ALR resume Sept 2015ALR resume Sept 2015
ALR resume Sept 2015specphrm
 
ребусы!!!
ребусы!!!ребусы!!!
ребусы!!!
guest28f4a2
 
Exibition Pitch: Eco-luxe fashion showcase
Exibition Pitch: Eco-luxe fashion showcaseExibition Pitch: Eco-luxe fashion showcase
Exibition Pitch: Eco-luxe fashion showcaseAisyah Bagarib
 
Vigilancia sanitaria Aedes aegypti en Chile Continental
Vigilancia sanitaria Aedes aegypti en Chile Continental Vigilancia sanitaria Aedes aegypti en Chile Continental
Vigilancia sanitaria Aedes aegypti en Chile Continental
Salud en todas
 
Atención de urgencia versus modelo de atención en APS
Atención de urgencia versus modelo de atención en APSAtención de urgencia versus modelo de atención en APS
Atención de urgencia versus modelo de atención en APS
Salud en todas
 
¿Es posible reconstruir un sistema de salud equitativo?
¿Es posible reconstruir un sistema de salud equitativo?¿Es posible reconstruir un sistema de salud equitativo?
¿Es posible reconstruir un sistema de salud equitativo?
Salud en todas
 
Formación y desarrollo profesional en salud pública
Formación y desarrollo profesional en salud públicaFormación y desarrollo profesional en salud pública
Formación y desarrollo profesional en salud pública
Salud en todas
 
How General Electric (GE) Saved 80% in Development Costs
How General Electric (GE) Saved 80% in Development CostsHow General Electric (GE) Saved 80% in Development Costs
How General Electric (GE) Saved 80% in Development Costs
Frances Goh
 
Mercedes s klasse-coupe preisliste Deutschland
Mercedes s klasse-coupe preisliste DeutschlandMercedes s klasse-coupe preisliste Deutschland
Mercedes s klasse-coupe preisliste Deutschland
steeringnews
 

Viewers also liked (11)

Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
REALIDAD AUMENTADA
REALIDAD AUMENTADAREALIDAD AUMENTADA
REALIDAD AUMENTADA
 
ALR resume Sept 2015
ALR resume Sept 2015ALR resume Sept 2015
ALR resume Sept 2015
 
ребусы!!!
ребусы!!!ребусы!!!
ребусы!!!
 
Exibition Pitch: Eco-luxe fashion showcase
Exibition Pitch: Eco-luxe fashion showcaseExibition Pitch: Eco-luxe fashion showcase
Exibition Pitch: Eco-luxe fashion showcase
 
Vigilancia sanitaria Aedes aegypti en Chile Continental
Vigilancia sanitaria Aedes aegypti en Chile Continental Vigilancia sanitaria Aedes aegypti en Chile Continental
Vigilancia sanitaria Aedes aegypti en Chile Continental
 
Atención de urgencia versus modelo de atención en APS
Atención de urgencia versus modelo de atención en APSAtención de urgencia versus modelo de atención en APS
Atención de urgencia versus modelo de atención en APS
 
¿Es posible reconstruir un sistema de salud equitativo?
¿Es posible reconstruir un sistema de salud equitativo?¿Es posible reconstruir un sistema de salud equitativo?
¿Es posible reconstruir un sistema de salud equitativo?
 
Formación y desarrollo profesional en salud pública
Formación y desarrollo profesional en salud públicaFormación y desarrollo profesional en salud pública
Formación y desarrollo profesional en salud pública
 
How General Electric (GE) Saved 80% in Development Costs
How General Electric (GE) Saved 80% in Development CostsHow General Electric (GE) Saved 80% in Development Costs
How General Electric (GE) Saved 80% in Development Costs
 
Mercedes s klasse-coupe preisliste Deutschland
Mercedes s klasse-coupe preisliste DeutschlandMercedes s klasse-coupe preisliste Deutschland
Mercedes s klasse-coupe preisliste Deutschland
 

Similar to Chapter 6 the django admin site

Introduction to Lago Web
Introduction to Lago WebIntroduction to Lago Web
Introduction to Lago Web
Fire Mountain Gems and Beads
 
Module 4 - Dreamweaver Templates (Static vs. Dynamic Content)
Module 4 - Dreamweaver Templates (Static vs. Dynamic Content)Module 4 - Dreamweaver Templates (Static vs. Dynamic Content)
Module 4 - Dreamweaver Templates (Static vs. Dynamic Content)
Katherine McCurdy-Lapierre, R.G.D.
 
How to customise Joomla
How to customise JoomlaHow to customise Joomla
How to customise Joomla
Tim Plummer
 
The Joy of Subforms with Randy Carey
The Joy of Subforms with Randy CareyThe Joy of Subforms with Randy Carey
The Joy of Subforms with Randy Carey
jdaychi
 
Open Source CMS Playroom
Open Source CMS PlayroomOpen Source CMS Playroom
Open Source CMS Playroomlibrarywebchic
 
WordPress theme setting page
WordPress theme setting pageWordPress theme setting page
WordPress theme setting page
Naeem Junejo
 
The very introduction to content management systems
The very introduction to content management systemsThe very introduction to content management systems
The very introduction to content management systems
Sean Donnelly BA MSc QFA
 
Webiny CMS Starter Guide
Webiny CMS Starter GuideWebiny CMS Starter Guide
Webiny CMS Starter Guide
Webiny
 
full-site-editing-theme-presentation.pptx
full-site-editing-theme-presentation.pptxfull-site-editing-theme-presentation.pptx
full-site-editing-theme-presentation.pptx
Plasterdog Web Design
 
WordPress Blogs 101
WordPress Blogs 101WordPress Blogs 101
WordPress Blogs 101
Tom McGee
 
WordPress can do that?!
WordPress can do that?!WordPress can do that?!
WordPress can do that?!
Scott McNulty
 
The WordPress University 2012
The WordPress University 2012The WordPress University 2012
The WordPress University 2012Stephanie Leary
 
Share point 2013 WCM for Developers
Share point 2013 WCM for DevelopersShare point 2013 WCM for Developers
Share point 2013 WCM for Developers
Suhas R Satish
 
JSLink for ITPros - SharePoint Saturday Jersey
JSLink for ITPros - SharePoint Saturday JerseyJSLink for ITPros - SharePoint Saturday Jersey
JSLink for ITPros - SharePoint Saturday Jersey
Paul Hunt
 
Apache Solr Search Course Drupal 7 Acquia
Apache Solr Search Course Drupal 7 AcquiaApache Solr Search Course Drupal 7 Acquia
Apache Solr Search Course Drupal 7 Acquia
Dropsolid
 
Joomla templates2011
Joomla templates2011Joomla templates2011
Joomla templates2011Linda Coonen
 
WordPress as a CMS
WordPress as a CMSWordPress as a CMS
WordPress as a CMS
Stephanie Leary
 
Jump to Joomla - Barcamp Nashville 2010
Jump to Joomla - Barcamp Nashville 2010Jump to Joomla - Barcamp Nashville 2010
Jump to Joomla - Barcamp Nashville 2010
Social LIfe Marketing, LLC
 

Similar to Chapter 6 the django admin site (20)

Introduction to Lago Web
Introduction to Lago WebIntroduction to Lago Web
Introduction to Lago Web
 
Module 4 - Dreamweaver Templates (Static vs. Dynamic Content)
Module 4 - Dreamweaver Templates (Static vs. Dynamic Content)Module 4 - Dreamweaver Templates (Static vs. Dynamic Content)
Module 4 - Dreamweaver Templates (Static vs. Dynamic Content)
 
How to customise Joomla
How to customise JoomlaHow to customise Joomla
How to customise Joomla
 
The Joy of Subforms with Randy Carey
The Joy of Subforms with Randy CareyThe Joy of Subforms with Randy Carey
The Joy of Subforms with Randy Carey
 
Inventor Content Center: Adding Information
Inventor Content Center:   Adding InformationInventor Content Center:   Adding Information
Inventor Content Center: Adding Information
 
Open Source CMS Playroom
Open Source CMS PlayroomOpen Source CMS Playroom
Open Source CMS Playroom
 
WordPress theme setting page
WordPress theme setting pageWordPress theme setting page
WordPress theme setting page
 
The very introduction to content management systems
The very introduction to content management systemsThe very introduction to content management systems
The very introduction to content management systems
 
Webiny CMS Starter Guide
Webiny CMS Starter GuideWebiny CMS Starter Guide
Webiny CMS Starter Guide
 
72d5drupal
72d5drupal72d5drupal
72d5drupal
 
full-site-editing-theme-presentation.pptx
full-site-editing-theme-presentation.pptxfull-site-editing-theme-presentation.pptx
full-site-editing-theme-presentation.pptx
 
WordPress Blogs 101
WordPress Blogs 101WordPress Blogs 101
WordPress Blogs 101
 
WordPress can do that?!
WordPress can do that?!WordPress can do that?!
WordPress can do that?!
 
The WordPress University 2012
The WordPress University 2012The WordPress University 2012
The WordPress University 2012
 
Share point 2013 WCM for Developers
Share point 2013 WCM for DevelopersShare point 2013 WCM for Developers
Share point 2013 WCM for Developers
 
JSLink for ITPros - SharePoint Saturday Jersey
JSLink for ITPros - SharePoint Saturday JerseyJSLink for ITPros - SharePoint Saturday Jersey
JSLink for ITPros - SharePoint Saturday Jersey
 
Apache Solr Search Course Drupal 7 Acquia
Apache Solr Search Course Drupal 7 AcquiaApache Solr Search Course Drupal 7 Acquia
Apache Solr Search Course Drupal 7 Acquia
 
Joomla templates2011
Joomla templates2011Joomla templates2011
Joomla templates2011
 
WordPress as a CMS
WordPress as a CMSWordPress as a CMS
WordPress as a CMS
 
Jump to Joomla - Barcamp Nashville 2010
Jump to Joomla - Barcamp Nashville 2010Jump to Joomla - Barcamp Nashville 2010
Jump to Joomla - Barcamp Nashville 2010
 

Recently uploaded

Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Pro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp BookPro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp Book
abdulrafaychaudhry
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Enterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptxEnterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptx
QuickwayInfoSystems3
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
abdulrafaychaudhry
 
AI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website CreatorAI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website Creator
Google
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 

Recently uploaded (20)

Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Pro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp BookPro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp Book
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Enterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptxEnterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptx
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
 
AI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website CreatorAI Genie Review: World’s First Open AI WordPress Website Creator
AI Genie Review: World’s First Open AI WordPress Website Creator
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 

Chapter 6 the django admin site

  • 1. Chapter 6:The Django Admin Site ⽑毛⽑毛
  • 2. Admin interface • A Web-based interface • Limited to trusted site administrators • Enable the adding, editing and deletion of site content • Some common examples • The interface you use to post to your blog • The backend site managers use to moderate user- generated comments
  • 3. The django.contrib packages • Contain various useful add-ons to the core framework • You can think of django.contrib as Django’s equivalent of the Python standard library • Django’s automatic admin is part of django.contrib • Other available features • A user authentication system (django.contrib.auth) • Anonymous sessions (django.contrib.sessions) • A system for user comments (django.contrib.comments)
  • 4. Activating the Admin Interface • The Django admin site is entirely optional • That means you’ll need to take a few steps to activate it in your project • First, make a few changes to your settings file • Add 'django.contrib.admin' to the INSTALLED_APPS setting • The order of INSTALLED_APPS doesn’t matter • Make sure INSTALLED_APPS contains 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages' and ‘django.contrib.sessions' • Make sure MIDDLEWARE_CLASSES contains 'django.middleware.common.CommonMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware'
  • 5. Activating the Admin Interface • Second, run python manage.py syncdb • Install the extra database tables that the admin interface uses • The first time you run syncdb, you’ll be asked about creating a superuser • To be able to log in to the admin site • If you don’t do this, you’ll need to run python manage.py createsuperuser separately • Third, add the admin site to your URLconf ! !
  • 6. Using the Admin Site • Run the development server • python manage.py runserver • Visit http://127.0.0.1:8000/admin/ in your Web browser ! ! ! !
  • 7. Using the Admin Site • Log in with the username and password you set up when you added your superuser • Once you’re logged in, the first thing you’ll see will be the admin home page • List all the available types of data that can be edited • The two default admin-editable models are only Groups and Users ! ! ! !
  • 8. Other languages • If your Web browser is configured to prefer a language other than English • Add 'django.middleware.locale.LocaleMiddleware' to your MIDDLEWARE_CLASSES setting • Make sure it appears after ‘django.contrib.sessions.middleware.SessionMiddleware' • Reload the admin index page • If a translation for your language is available, you will see the change • Django ships with translations for dozens of languages
  • 9. Using the Admin Site • Click the “Change” link in the “Users” row to load the change list page for users • This page displays all users in the database • There are useful filtering, sorting and searching options • Filtering options are at right, sorting is available by clicking a column header, and the search box at the top lets you search by username ! ! ! !
  • 10. Using the Admin Site • Click the username of the user you created, and you’ll see the edit form for that user • This page lets you change the attributes of the user, like the first/last names and various permissions • To change a user’s password, you should click “change password form” under the password field rather than editing the hashed code • You can delete a record by clicking the delete button at the bottom left of its edit form • You can add a record by clicking “Add” in the appropriate column of the admin home page • Admin interface also handles input validation ! !
  • 11. Using the Admin Site • When you edit an existing object, you’ll notice a History link in the upper-right corner of the window • Every change made through the admin interface is logged, and you can examine this log by clicking the History link ! ! ! !
  • 12. Adding Your Models to the Admin Site • Add our own models to the admin site, so we can add, change and delete objects in our custom database tables using this nice interface • Continue the books example from Chapter 5, where we defined three models: Publisher, Author and Book • Within the books directory (mysite/books), create a file called admin.py ! ! ! ! • This code tells the Django admin site to offer an interface for each of these models
  • 13. Adding Your Models to the Admin Site • The admin site can handle foreign keys and many-to-many relationships ! ! ! ! ! • The publisher (a ForeignKey) is represented by a select box • The authors field (a ManyToManyField) is represented by a multiple-select box • Both fields sit next to a green plus sign icon that lets you add related records of that type
  • 14. Making Fields Optional • By default, all fields have blank=False, which means blank values are not allowed • Make email field optional • Add blank=True to the email field ! ! • On the Admin Site, you’ll notice the field’s label – “Email” – is no longer bolded
  • 15. Making Fields Optional • Make date and numeric fields optional • Use both null=True and blank=True ! ! ! • Adding null=True is more complicated than adding blank=True, because null=True changes the semantics of the database • To complete this change, we’ll need to update the database • Django does not attempt to automate changes to database schemas, so it’s your own responsibility to execute the appropriate ALTER TABLE statement • Use manage.py dbshell to enter your database server’s shell.
  • 16. Customizing Field Labels • On the admin site’s edit forms, each field’s label is generated from its model field name • Django just replaces underscores with spaces and capitalizes the first character • The Book model’s publication_date field has the label “Publication date” • However, field names don’t always lend themselves to nice admin field labels, so in some cases you might want to customize a label • By specifying verbose_name in the appropriate model field ! ! ! • Note that you shouldn’t capitalize the first letter of a verbose_name unless it should always be capitalized • Django will automatically capitalize it when it needs to
  • 17. Custom ModelAdmin classes • The Django admin site offers a wealth of options that let you customize how the admin site works for a particular model • Such options live in ModelAdmin classes • Customizing change lists • By default, the change list displays the result of __unicode__() for each object • In Chapter 5, we defined the __unicode__() method for Author objects to display the first name and last name together ! ! !
  • 18. Custom ModelAdmin classes • We can improve on this default behavior by adding a few other fields to the change list display • To see each author’s e-mail address in this list, and it’d be nice to be able to sort by first and last name • To make this happen, we’ll define a ModelAdmin class for the Author model • This class is the key to customizing the admin • Edit admin.py to make these changes ! ! !
  • 19. Custom ModelAdmin classes • Create the class AuthorAdmin, which subclasses ModelAdmin, holds custom configuration for a specific admin model • One customization – list_display, which is set to a tuple of field names to display on the change list page. • These field names must exist in the model • Altere the admin.site.register(). You can read this as: “Register the Author model with the AuthorAdmin options.” ! ! ! !
  • 20. Custom ModelAdmin classes • Next, let’s add a simple search bar • Add search_fields to the AuthorAdmin ! ! • Reload the page in your browser, and you should see a search bar at the top • Search against the first_name and last_name fields • Is case-insensitive and searches both fields • Search for the string "bar" would find both an author with the first name Barney and an author with the last name Hobarson !
  • 21. Custom ModelAdmin classes • Next, let’s add some date filters to our Book model’s change list page ! ! ! !
  • 22. Custom ModelAdmin classes • list_filter, which is set to a tuple of fields to use to create filters along the right side of the change list page • Django provides shortcuts to filter the list to “Today,” “Past 7 days,” “This month” and “This year” ! ! ! ! ! • list_filter also works on fields of other types, not just DateField • As long as there are at least 2 values to choose from
  • 23. Custom ModelAdmin classes • Another way to offer date filters is to use the date_hierarchy admin option • The change list page gets a date drill-down navigation bar at the top of the list • It starts with a list of available years, then drills down into months and individual days • Note that date_hierarchy takes a string, not a tuple, because only one date field can be used to make the hierarchy ! ! ! ! !
  • 24. Custom ModelAdmin classes • let’s change the default ordering so that books on the change list page are always ordered descending by their publication date • By default, the change list orders objects according to their model’s ordering within class Meta • ordering - Just pass a list or tuple of field names, and add a minus sign to a field to use descending sort order ! ! ! !
  • 25. Custom ModelAdmin classes • Customizing edit forms • First, let’s customize the way fields are ordered • By default, the order of fields in an edit form corresponds to the order they’re defined in the model • Use the fields option in our ModelAdmin subclass ! ! ! • After this change, the edit form for books will use the given ordering for fields
  • 26. Custom ModelAdmin classes • Another useful thing the fields option lets you do is to exclude certain fields from being edited entirely • Just leave out the field(s) you want to exclude • You might use this if your admin users are only trusted to edit a certain segment of your data • For example, in our book database, we could hide the publication_date field from being editable ! ! !
  • 27. Custom ModelAdmin classes • As a result, the edit form for books doesn’t offer a way to specify the publication date • When a user uses this incomplete form to add a new book, Django will simply set the publication_date to None • Make sure that field has null=True ! ! !
  • 28. Custom ModelAdmin classes • Customization for many-to-many fields • The admin site represents each ManyToManyField as a multiple-select boxes • Multiple-select boxes can be difficult to use • The admin site’s solution is filter_horizontal ! ! ! !
  • 29. Custom ModelAdmin classes ! ! ! ! ! • Highly recommend using filter_horizontal for any ManyToManyField that has more than 10 items • ModelAdmin classes also support a filter_vertical option • This works exactly as filter_horizontal, but the resulting JavaScript interface stacks the two boxes vertically instead of horizontally • filter_horizontal and filter_vertical only work on ManyToManyField fields, not ForeignKey fields
  • 30. Custom ModelAdmin classes • Sometimes you don’t want to incur the overhead of having to select all the related objects to display in the drop-down • For example, if our book database grows to include thousands of publishers, the “Add book” form could take a while to load, because it would have to load every publisher for display in the <select> box • The way to fix this is to use an option called raw_id_fields ! ! ! ! !
  • 31. Users, Groups, and Permissions • If you’re logged in as a superuser, you have access to create, edit, and delete any object • Naturally, different environments require different permission systems • Django’s admin site uses a permissions system • You can edit users and permissions through the admin interface just like any other object • There’s a set of three boolean flags • The “active” flag controls whether the user is active at all • If this flag is off and the user tries to log in, he won’t be allowed in, even with a valid password • The “staff” flag controls whether the user is allowed to log in to the admin interface • This flag differentiates between public users and administrators • The “superuser” flag gives the user full access to add, create and delete any item in the admin interface
  • 32. Users, Groups, and Permissions • Each object editable through the admin interface has three permissions: a create permission, an edit permission and a delete permission • When you create a user, that user has no permissions, and it’s up to you to give the user specific permissions • These permissions are defined per-model, not per-object • So they let you say “John can make changes to any book,” but they don’t let you say “John can make changes to any book published by Apress.” • You can also assign users to groups • A group is simply a set of permissions to apply to all members of that group • Groups are useful for granting identical permissions to a subset of users
  • 33. When and Why to Use the Admin Interface – And When Not to • Django’s admin site especially shines when nontechnical users need to be able to enter data • Django’s admin interface is facilitating the simultaneous work of content producers and programmers • Beyond these obvious data entry tasks, the admin site is useful in a few other cases • Inspecting data models • Managing acquired data • Quick and dirty data-management apps • The admin site is not intended to be a public interface to data, nor is it intended to allow for sophisticated sorting and searching of your data • It is for trusted site administrators