SlideShare a Scribd company logo
Django Admin
Widgetry & Witchery


Pamela Fox
@pamelafox
Coursera: What we do
Our Backend
Why We Need Admin
Why Django Admin?
Creates forms for adding/editing/searching models

Restricts fields based on admin roles
How Django Admin Works
                                           from   django.contrib import admin
                                           from   app import admin
                                           from   app.courses.models import Course
                                           from   app.courses.forms import CourseAdminForm

                                           class CourseAdmin(ModelAdmin):
                                               base_model = Course
                                               restrict_fields = ['instructors', 'teaching_assistants', ]
                                               form = CourseAdminForm
                                               fieldsets = [
                                                   (None, {
                                                       'fields': [
                                                            'name',
                                                            'topic',
                                                            'active',
                                                       ]
                                                   }),
                                                   ('Dates', {
                                                       'fields': [
                                                            'start_date',
                                                            'end_date',
                                                            'start_date_string',
                                                            'duration_string',
                                                       ]
                                                   })
                                               ]

                                           admin.site.register(Course, CourseAdmin)




https://docs.djangoproject.com/en/dev/ref/contrib/admin/
...And a few words on
how it doesn’t work.
☹: The Look & Feel


       !=
Solution:    Twitter Bootstrap




https://github.com/gkuhn1/django-admin-templates-twitter-bootstrap
☹: The Default Widgets
BooleanField       FilePathField              RegexField

CharField          FloatField                 SlugField

ChoiceField        ImageField                 TimeField

TypedChoiceField   IntegerField               URLField

DateField          IPAddressField             ComboField

DateTimeField      GenericIPAddressField      MultiValueField

DecimalField       MultipleChoiceField        SplitDateTimeField

EmailField         TypedMultipleChoiceField   ModelChoiceField

FileField          NullBooleanField           ModelMultipleChoiceField
Solution:        Custom Widgets
TransloaditUpload      WysiHTMLEditor




NumberField               NumberRangeField


                                             AutoCompleteTextInput



 UniqueShortName
Custom Widgets
    admin/common/widgets.py:

class NumberField(HiddenInput):
    class Media:
        js = (
            settings.ADMIN_MEDIA_PREFIX + 'js/numberfields.js',
            )

    def render(self, name, value, attrs=None):
        input = super(NumberField, self).render(name, value, attrs=attrs)
        final_attrs = self.build_attrs(attrs)
        units = final_attrs.get('units', '')
        html = u"""
        <div class="number-field">
        %(input)s
        <input type="number" min="1" class="number-range-field-num input-mini">
        <span class="number-range-field-units">%(units)s<span>
        </div>
        """ % {'input': input, 'units': units}
        return mark_safe(html)




   course/admin.py                                                course/forms.py

from app import admin                                       from django.forms import ModelForm
from app.courses.models import Course                       from app.common.widgets import NumberField
from app.courses.forms import CourseAdminForm

                                                            class CourseAdminForm(ModelForm):
class CourseAdmin(ModelAdmin):                                  class Meta:
    base_model = Course                                             widgets = {
                                                                        'duration_string': NumberField(
    form = CourseAdminForm                                                  attrs={'units': 'weeks'})
                                                                        }
☹: Default Save Options


       !=
Solution:          Horrible Hacks
   templates/admin/change_form.html

var topicPageRegEx = //topics/topic//i;
var isTopicPage = topicPageRegEx.exec(window.location.href);
if (isTopicPage) {
  var previewHosts = {'admin': 'site', 'admin.coursera.org': 'www.coursera.org'};
  var previewUrl = 'http://' + previewHosts[window.location.host] + '/course/' + $
('input[name="short_name"]').val();
  var $previewUrl = $('<input type="hidden" name="_previewurl">').val(previewUrl);
  var $previewButton = $('<input type="submit" name="_saveandpreview" value="Save and Preview" class="btn
btn-info">');
  var $saveButton = $('.form-actions input[name="_save"]')
  $saveButton.after('&nbsp;').after($previewButton)
     .after('&nbsp;').after($previewUrl);
}




   admin/options.py

if "_saveandpreview" in request.POST:
      return HttpResponseRedirect(request.POST['_previewurl'])
In conclusion...
Our Future Admin Stack?




https://github.com/PaulUithol/backbone-tastypie   https://github.com/joshbohde/django-backbone-example

More Related Content

What's hot (20)

PPTX
Modules and injector
Eyal Vardi
 
PDF
Dependency Management with RequireJS
Aaronius
 
PDF
Odoo Experience 2018 - Develop an App with the Odoo Framework
ElínAnna Jónasdóttir
 
PDF
JavaScript for Flex Devs
Aaronius
 
PDF
RequireJS & Handlebars
Ivano Malavolta
 
PPTX
Odoo (Build module, Security, ORM)
sroo galal
 
PDF
Introduction to backbone presentation
Brian Hogg
 
PDF
Make your App Frontend Compatible
Odoo
 
PDF
Django design-patterns
Agiliq Info Solutions India Pvt Ltd
 
PPTX
Xml operations in odoo
Celine George
 
PDF
Odoo Experience 2018 - The Odoo JS Framework
ElínAnna Jónasdóttir
 
PDF
Javascript MVC & Backbone Tips & Tricks
Hjörtur Hilmarsson
 
PDF
Odoo Experience 2018 - Inherit from These 10 Mixins to Empower Your App
ElínAnna Jónasdóttir
 
PPTX
Angular 2.0 forms
Eyal Vardi
 
PPTX
Angular 2 Architecture (Bucharest 26/10/2016)
Eyal Vardi
 
PDF
[FEConf Korea 2017]Angular 컴포넌트 대화법
Jeado Ko
 
PDF
AngularJS vs. Ember.js vs. Backbone.js
Mark
 
PPTX
Performance Optimization In Angular 2
Eyal Vardi
 
PDF
Django class based views for beginners
Spin Lai
 
PDF
Handlebars.js
Ivano Malavolta
 
Modules and injector
Eyal Vardi
 
Dependency Management with RequireJS
Aaronius
 
Odoo Experience 2018 - Develop an App with the Odoo Framework
ElínAnna Jónasdóttir
 
JavaScript for Flex Devs
Aaronius
 
RequireJS & Handlebars
Ivano Malavolta
 
Odoo (Build module, Security, ORM)
sroo galal
 
Introduction to backbone presentation
Brian Hogg
 
Make your App Frontend Compatible
Odoo
 
Django design-patterns
Agiliq Info Solutions India Pvt Ltd
 
Xml operations in odoo
Celine George
 
Odoo Experience 2018 - The Odoo JS Framework
ElínAnna Jónasdóttir
 
Javascript MVC & Backbone Tips & Tricks
Hjörtur Hilmarsson
 
Odoo Experience 2018 - Inherit from These 10 Mixins to Empower Your App
ElínAnna Jónasdóttir
 
Angular 2.0 forms
Eyal Vardi
 
Angular 2 Architecture (Bucharest 26/10/2016)
Eyal Vardi
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
Jeado Ko
 
AngularJS vs. Ember.js vs. Backbone.js
Mark
 
Performance Optimization In Angular 2
Eyal Vardi
 
Django class based views for beginners
Spin Lai
 
Handlebars.js
Ivano Malavolta
 

Viewers also liked (10)

PDF
A Year of Hermit Hacking
Pamela Fox
 
PDF
Teaching Programming Online
Pamela Fox
 
PDF
Engineering culture
Pamela Fox
 
PDF
The Developer Experience
Pamela Fox
 
PDF
Présentation RIA avec Adobe Flex / RIA with Adobe Flex
Cynapsys It Hotspot
 
PPT
OpenSocial Intro
Pamela Fox
 
PPT
Flex vs. HTML5 for RIAS
Pamela Fox
 
PPT
Client Killed the Server Star
Pamela Fox
 
PDF
Making JavaScript Libraries More Approachable
Pamela Fox
 
PPT
No, Really, I'm Shy
Pamela Fox
 
A Year of Hermit Hacking
Pamela Fox
 
Teaching Programming Online
Pamela Fox
 
Engineering culture
Pamela Fox
 
The Developer Experience
Pamela Fox
 
Présentation RIA avec Adobe Flex / RIA with Adobe Flex
Cynapsys It Hotspot
 
OpenSocial Intro
Pamela Fox
 
Flex vs. HTML5 for RIAS
Pamela Fox
 
Client Killed the Server Star
Pamela Fox
 
Making JavaScript Libraries More Approachable
Pamela Fox
 
No, Really, I'm Shy
Pamela Fox
 
Ad

Similar to Django Admin: Widgetry & Witchery (20)

PDF
Django 1.4-cheatsheet
Daniel Pimenta
 
PDF
Web Development Paradigms and djangoic approach to deal with them
Lakshman Prasad
 
PDF
Django admin
Petter Arvidsson
 
PDF
How symfony2 forms_works
Amardeep Aryan
 
PDF
What’S New In Newforms Admin
DjangoCon2008
 
PDF
djangoic approach to implement common web development paradigms
Lakshman Prasad
 
KEY
Admin
soon
 
PDF
Forms, Getting Your Money's Worth
Alex Gaynor
 
PDF
Chapter 6 the django admin site
家璘 卓
 
PDF
Introduction To Django (Strange Loop 2011)
Jacob Kaplan-Moss
 
PPTX
Django in the Office: Get Your Admin for Nothing and Your SQL for Free
Harvard Web Working Group
 
PDF
Working With The Symfony Admin Generator
John Cleveley
 
PPT
Django Forms: Best Practices, Tips, Tricks
Shawn Rider
 
PDF
那些年,我用 Django Admin 接的案子
flywindy
 
PDF
Customizing the Django Admin
Lincoln Loop
 
PDF
Class-based views with Django
Simon Willison
 
PDF
Django - basics
University of Technology
 
KEY
Django quickstart
Marconi Moreto
 
PDF
Symfony Admin Generator
Nuuktal Consulting
 
PPTX
Widgets in odoo
Celine George
 
Django 1.4-cheatsheet
Daniel Pimenta
 
Web Development Paradigms and djangoic approach to deal with them
Lakshman Prasad
 
Django admin
Petter Arvidsson
 
How symfony2 forms_works
Amardeep Aryan
 
What’S New In Newforms Admin
DjangoCon2008
 
djangoic approach to implement common web development paradigms
Lakshman Prasad
 
Admin
soon
 
Forms, Getting Your Money's Worth
Alex Gaynor
 
Chapter 6 the django admin site
家璘 卓
 
Introduction To Django (Strange Loop 2011)
Jacob Kaplan-Moss
 
Django in the Office: Get Your Admin for Nothing and Your SQL for Free
Harvard Web Working Group
 
Working With The Symfony Admin Generator
John Cleveley
 
Django Forms: Best Practices, Tips, Tricks
Shawn Rider
 
那些年,我用 Django Admin 接的案子
flywindy
 
Customizing the Django Admin
Lincoln Loop
 
Class-based views with Django
Simon Willison
 
Django - basics
University of Technology
 
Django quickstart
Marconi Moreto
 
Symfony Admin Generator
Nuuktal Consulting
 
Widgets in odoo
Celine George
 
Ad

More from Pamela Fox (20)

PPT
How I became a born again vegetable-tarian
Pamela Fox
 
KEY
The Developer Experience
Pamela Fox
 
PPT
Writing Apps the Google-y Way (Brisbane)
Pamela Fox
 
PPT
Writing Apps the Google-y Way
Pamela Fox
 
PPT
The Wonders of the "Onesie"
Pamela Fox
 
PPT
I’M A Barbie Girl In A CS World
Pamela Fox
 
PPT
Google Wave 20/20: Product, Protocol, Platform
Pamela Fox
 
PPT
Collaborative Mapping with Google Wave
Pamela Fox
 
PPT
Google Products: Deep Dive on Google Maps
Pamela Fox
 
PPT
Google Products & Google Maps
Pamela Fox
 
PPT
Mashups & APIs
Pamela Fox
 
PPT
A World of Words
Pamela Fox
 
PPT
Web APIs & Google APIs
Pamela Fox
 
PPT
Growing up Geek: My Dad, the Computer Scientist
Pamela Fox
 
PPT
Living in the Cloud: Hosting Data & Apps Using the Google Infrastructure
Pamela Fox
 
PPT
NORAD Santa Tracker: Tips & Tricks
Pamela Fox
 
PPT
Socializing Apps
Pamela Fox
 
PPT
Open Maps (Or Close Enough?)
Pamela Fox
 
PPT
Gadgets Intro (Plus Mapplets)
Pamela Fox
 
PPT
Data-Driven Facial Animation Based on Feature Points
Pamela Fox
 
How I became a born again vegetable-tarian
Pamela Fox
 
The Developer Experience
Pamela Fox
 
Writing Apps the Google-y Way (Brisbane)
Pamela Fox
 
Writing Apps the Google-y Way
Pamela Fox
 
The Wonders of the "Onesie"
Pamela Fox
 
I’M A Barbie Girl In A CS World
Pamela Fox
 
Google Wave 20/20: Product, Protocol, Platform
Pamela Fox
 
Collaborative Mapping with Google Wave
Pamela Fox
 
Google Products: Deep Dive on Google Maps
Pamela Fox
 
Google Products & Google Maps
Pamela Fox
 
Mashups & APIs
Pamela Fox
 
A World of Words
Pamela Fox
 
Web APIs & Google APIs
Pamela Fox
 
Growing up Geek: My Dad, the Computer Scientist
Pamela Fox
 
Living in the Cloud: Hosting Data & Apps Using the Google Infrastructure
Pamela Fox
 
NORAD Santa Tracker: Tips & Tricks
Pamela Fox
 
Socializing Apps
Pamela Fox
 
Open Maps (Or Close Enough?)
Pamela Fox
 
Gadgets Intro (Plus Mapplets)
Pamela Fox
 
Data-Driven Facial Animation Based on Feature Points
Pamela Fox
 

Recently uploaded (20)

PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PDF
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
PDF
July Patch Tuesday
Ivanti
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PPTX
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PDF
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
PDF
Python basic programing language for automation
DanialHabibi2
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
July Patch Tuesday
Ivanti
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
Python basic programing language for automation
DanialHabibi2
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 

Django Admin: Widgetry & Witchery

  • 1. Django Admin Widgetry & Witchery Pamela Fox @pamelafox
  • 4. Why We Need Admin
  • 5. Why Django Admin? Creates forms for adding/editing/searching models Restricts fields based on admin roles
  • 6. How Django Admin Works from django.contrib import admin from app import admin from app.courses.models import Course from app.courses.forms import CourseAdminForm class CourseAdmin(ModelAdmin): base_model = Course restrict_fields = ['instructors', 'teaching_assistants', ] form = CourseAdminForm fieldsets = [ (None, { 'fields': [ 'name', 'topic', 'active', ] }), ('Dates', { 'fields': [ 'start_date', 'end_date', 'start_date_string', 'duration_string', ] }) ] admin.site.register(Course, CourseAdmin) https://docs.djangoproject.com/en/dev/ref/contrib/admin/
  • 7. ...And a few words on how it doesn’t work.
  • 8. ☹: The Look & Feel !=
  • 9. Solution: Twitter Bootstrap https://github.com/gkuhn1/django-admin-templates-twitter-bootstrap
  • 10. ☹: The Default Widgets BooleanField FilePathField RegexField CharField FloatField SlugField ChoiceField ImageField TimeField TypedChoiceField IntegerField URLField DateField IPAddressField ComboField DateTimeField GenericIPAddressField MultiValueField DecimalField MultipleChoiceField SplitDateTimeField EmailField TypedMultipleChoiceField ModelChoiceField FileField NullBooleanField ModelMultipleChoiceField
  • 11. Solution: Custom Widgets TransloaditUpload WysiHTMLEditor NumberField NumberRangeField AutoCompleteTextInput UniqueShortName
  • 12. Custom Widgets admin/common/widgets.py: class NumberField(HiddenInput): class Media: js = ( settings.ADMIN_MEDIA_PREFIX + 'js/numberfields.js', ) def render(self, name, value, attrs=None): input = super(NumberField, self).render(name, value, attrs=attrs) final_attrs = self.build_attrs(attrs) units = final_attrs.get('units', '') html = u""" <div class="number-field"> %(input)s <input type="number" min="1" class="number-range-field-num input-mini"> <span class="number-range-field-units">%(units)s<span> </div> """ % {'input': input, 'units': units} return mark_safe(html) course/admin.py course/forms.py from app import admin from django.forms import ModelForm from app.courses.models import Course from app.common.widgets import NumberField from app.courses.forms import CourseAdminForm class CourseAdminForm(ModelForm): class CourseAdmin(ModelAdmin): class Meta: base_model = Course widgets = { 'duration_string': NumberField( form = CourseAdminForm attrs={'units': 'weeks'}) }
  • 13. ☹: Default Save Options !=
  • 14. Solution: Horrible Hacks templates/admin/change_form.html var topicPageRegEx = //topics/topic//i; var isTopicPage = topicPageRegEx.exec(window.location.href); if (isTopicPage) { var previewHosts = {'admin': 'site', 'admin.coursera.org': 'www.coursera.org'}; var previewUrl = 'http://' + previewHosts[window.location.host] + '/course/' + $ ('input[name="short_name"]').val(); var $previewUrl = $('<input type="hidden" name="_previewurl">').val(previewUrl); var $previewButton = $('<input type="submit" name="_saveandpreview" value="Save and Preview" class="btn btn-info">'); var $saveButton = $('.form-actions input[name="_save"]') $saveButton.after('&nbsp;').after($previewButton) .after('&nbsp;').after($previewUrl); } admin/options.py if "_saveandpreview" in request.POST: return HttpResponseRedirect(request.POST['_previewurl'])
  • 16. Our Future Admin Stack? https://github.com/PaulUithol/backbone-tastypie https://github.com/joshbohde/django-backbone-example

Editor's Notes