The newforms-admin branch

This branch has been merged into trunk as of [7967].

This branch aims to integrate Django's admin site with the newforms library. Along the way, we're taking the opportunity to add extra customization hooks to the admin site.

A HOWTO on customizing the newforms admin can be found here: NewformsHOWTO

How to get the branch

svn co http://code.djangoproject.com/svn/django/branches/newforms-admin/

See our branch policy for full information on how to use a branch.

Goals

The main goals of this branch are:

  • Change the admin site to use newforms instead of automatic manipulators.
  • Enable developers to declare custom widgets for particular fields in a model.
  • Enable developers to declare custom admin-only validation for a model (i.e., validation logic that is applied only in the admin site, nowhere else).
  • Give developers extra hooks into the admin-site functionality. (Yes, this is a broad goal. More examples are forthcoming.)
  • Remove the admin declarations (class Admin) from within models, thereby helping decouple the admin system from models.
  • Integrate some ideas from #2248: Remove core=True, specify inline models in the model itself rather than in the related model, specify which fields should be displayed inline.

The django.contrib.formtools.preview.FormPreview application elegantly allows for fine-grained customization of the application by subclassing. We're taking a similar approach for the new version of the Django admin site: Write a class that subclasses a base class called ModelAdmin and specify whichever customizations you need to make -- from the current basic admin options such as list_display and search_fields to full-on Python hooks, such as defining arbitrary Python code to run before or after a model object is saved via the admin.

Status

A lot has changed in this branch. Let's start with the syntax for URLconfs:

# OLD:
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^admin/', include('django.contrib.admin.urls')),
)

# NEW:
from django.conf.urls.defaults import *
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
    (r'^admin/(.*)', admin.site.root),
)

Note that, in this above URLconf example, we're dealing with the object django.contrib.admin.site. This is an instance of django.contrib.admin.AdminSite, which is a class that lets you specify admin-site functionality. The object django.contrib.admin.site is a default AdminSite instance that is created for you automatically, but you can also create other instances as you see fit.

We use the admin.autodiscover() call above to force the import of the admin.py module of each INSTALLED_APPS entry. This won't be needed if you use your own AdminSite instance since you will likely be importing those modules explicily in a project-level admin.py. This was added in [7872].

Previously, there was one "global" version of the admin site, which used all models that contained a class Admin. This new scheme allows for much more fine-grained control over your admin sites, allowing you to have multiple admin sites in the same Django instance.

In this example, we create two AdminSite instances, registering different models with both. Assume Book, Author, Musician and Instrument are Django model classes (not instances).

# project-level admin.py

from django.contrib import admin
from myproject.myapp.models import Book, Author
from myproject.anotherapp.models import Musician, Instrument

site1 = admin.AdminSite()
site1.register(Book)
site1.register(Author)

site2 = admin.AdminSite()
site2.register(Musician)
site2.register(Instrument)

# URLconf

from django.conf.urls.defaults import *
from myproject.admin import site1, site2

urlpatterns = patterns('',
    (r'^book_admin/(.*)', site1.root),
    (r'^music_admin/(.*)', site2.root),
)

With this example, if you go to /book_admin/, you'll get a Django admin site for the Book and Author models. If you go to /music_admin/, you'll get a Django admin site for the Musician and Instrument models.

Admin options -- the inner class Admin -- have changed, too. Models no longer use an inner class to declare their admin site options. In fact, all admin functionality has been decoupled from the model syntax! How, then, do we declare admin options? Like this:

# a sample models.py file
from django.db import models

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

    def __unicode__(self):
        return u'%s %s' % (self.first_name, self.last_name)

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author)

# a sample admin.py file (in same app)
from django.contrib import admin
from myproject.myapp.models import Author, Book

class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'author')
    ordering = ('title',)

admin.site.register(Author)
admin.site.register(Book, BookAdmin)

In this example, we register both Author and Book with the AdminSite instance django.contrib.admin.site. Author doesn't need any custom admin options, so we just call admin.site.register(Author). Book, on the other hand, has some custom admin options, so we define a BookAdmin class and pass that class as a second argument to admin.site.register().

You'll notice the BookAdmin class looks a lot like the old-style class Admin. Almost all of the old class Admin options work exactly the same, with one or two exceptions. (For the options that have changed, we've made them much more powerful.) In addition to the classic options such as list_display and ordering, the ModelAdmin class introduces a wealth of extra hooks you can use to customize the admin site for that particular model. For example:

class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'author')
    ordering = ('title',)

    def has_change_permission(self, request, obj=None):
        """
        John can only edit books by Roald Dahl.
        """
        if obj and request.user.username == 'john':
            return obj.author.last_name == 'Dahl'
        return super(BookAdmin, self).has_change_permission(request, obj)

Look at the class ModelAdmin in the file [source:/django/branches/newforms-admin/django/contrib/admin/options.py django/contrib/admin/options.py] to see all of the methods you can override. This is exciting stuff.

To-do list

Backwards-incompatible changes

This is a (currently incomplete) list of backwards-incompatible changes made in this branch.

Changed Admin.manager option to more flexible hook

As of [4342], the manager option to class Admin no longer exists. This option was undocumented, but we're mentioning the change here in case you used it. In favor of this option, class Admin may now define a queryset method:

class BookAdmin(admin.ModelAdmin):
    def queryset(self, request):
        """
        Filter based on the current user.
        """
        return self.model._default_manager.filter(user=request.user)

Changed prepopulate_from to be defined in the Admin class, not database field classes

As of [4446], the prepopulate_from option to database fields no longer exists. It's been discontinued in favor of the new prepopulated_fields option on class Admin. The new prepopulated_fields option, if given, should be a dictionary mapping field names to lists/tuples of field names. This change was made in an effort to remove admin-specific options from the model itself. Here's an example comparing old syntax and new syntax:

# OLD:
class MyModel(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    slug = models.CharField(max_length=60, prepopulate_from=('first_name', 'last_name'))

    class Admin:
        pass

# NEW:
class MyModel(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    slug = models.CharField(max_length=60)

from django.contrib import admin

class MyModelAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('first_name', 'last_name')}

admin.site.register(MyModel, MyModelAdmin)

Moved admin doc views into django.contrib.admindocs

As of [4585], the documentation views for the Django admin site were moved into a new package, django.contrib.admindocs.

The admin docs, which aren't documented very well, were located at docs/ in the admin site. They're also linked-to by the "Documentation" link in the upper right of default admin templates.

Because we've moved the doc views, you now have to activate admin docs explicitly. Do this by adding the following line to your URLconf:

    (r'^admin/doc/', include('django.contrib.admindocs.urls')),

You have to add this line before r'^admin(.*)' otherwise it won't work.

Renamed 'fields' to 'fieldsets', and changed type of 'classes' value

'Fields' is used to order and group fields in the change form layout.
It is still available in the new admin, but it accepts only a list of fields.
In case one uses fieldsets to organize the fields, one needs to use 'fieldsets' instead.
Also, if 'classes' is specified in a field specification, then the type of its value needs to be changed from a string to a tuple of strings when migrating to the new 'fieldsets' specification.

An example:

# OLD:
class MyModelA(models.Model):
   class Admin:
     fields = ('field1','field2','field3','field4')

class MyModelB(models.Model):
   class Admin:
     fields = (
         ('group1', {'fields': ('field1','field2'), 'classes': 'collapse'}),
         ('group2', {'fields': ('field3','field4'), 'classes': 'collapse wide'}),
     )

# NEW:
class MyModelAdmin(admin.ModelAdmin):
    fields = ('field1', 'field2', 'field3', 'field4')  # Renaming is optional 

class AnotherModelAdmin(admin.ModelAdmin):
     fieldsets = (
         ('group1', {'fields': ('field1','field2'), 'classes': ('collapse',)}),
         ('group2', {'fields': ('field3','field4'), 'classes': ('collapse', 'wide')}),
     )

Inline editing

The syntax is now different and much, much better. Here is an example:

from django.contrib import admin 

class ChildInline(admin.TabularInline): 
    model = Child 
    extra = 3 

class ParentAdmin(admin.ModelAdmin):
    model = Parent
    inlines = [ChildInline]

See this documentation for more details on field options for inline classes

Refactored inner Admin js option to media definitions

In [5926] a new method of dealing with media definitions was added. It is now much more flexible and allows media on more than just a ModelAdmin classes.

An example:

# OLD:
class MyModel(models.Model):
    # not relavent, but here for show
    field1 = models.CharField(max_length=100)
    
    class Admin:
        js = (
            "/static/my_code.js",
        )

# NEW:
# in admin.py

class MyModelAdmin(admin.ModelAdmin):
    class Media:
        js = (
            "/static/my_code.js",
        )

One very subtle thing to note is previously with trunk the documentation stated:

If you use relative URLs — URLs that don’t start with http:// or / — then the admin site will automatically prefix these links with settings.ADMIN_MEDIA_PREFIX.

Which is still partially true with newforms-admin, but now when using relative URLs settings.MEDIA_URL is prepended and not settings.ADMIN_MEDIA_PREFIX. If you are still looking for the old behavior you can accomplish it by doing the following:

from django.conf import settings

class MyModelAdmin(admin.ModelAdmin):
    class Media:
        js = (
            settings.ADMIN_MEDIA_PREFIX + "some_file.js",
        )

Make sure the value of settings.ADMIN_MEDIA_PREFIX is a proper absolute URL otherwise it will be treated the same as a relative URL.

Moved raw_id_admin from the model definition

The syntax is now separated from the definition of your models.

An example:

# OLD:
class MyModel(models.Model): 
    field1 = models.ForeignKey(AnotherModel, raw_id_admin=True)
    
    class Admin:
        pass

# NEW:
class MyModelAdmin(admin.ModelAdmin):
    model = MyModel
    raw_id_fields = ('field1',) 

django.contrib.auth is now using newforms

In [7191] django.contrib.auth has been converted to use newforms as opposed to using oldforms. If you are relying on the oldforms, you will need to modify your code/templates to work with newforms.

Moved radio_admin from the model definition

An example:

# OLD:
class MyModel(models.Model): 
    field1 = models.ForeignKey(AnotherModel, radio_admin=models.VERTICAL)
    
    class Admin:
        pass

# NEW:
class MyModelAdmin(admin.ModelAdmin):
    model = MyModel
    radio_fields = {'field1': admin.VERTICAL}

Moved filter_interface from the model definition

An example:

# OLD:
class MyModel(models.Model):
    field1 = models.ManyToManyField(AnotherModel, filter_interface=models.VERTICAL)
    field2 = models.ManyToManyField(YetAnotherModel, filter_interface=models.HORIZONTAL)

# NEW:
class MyModelAdmin(admin.ModelAdmin):
    filter_vertical = ('field1',)
    filter_horizontal = ('field2',)

Step by step migration screencast

http://oebfare.com/blog/2008/jul/20/newforms-admin-migration-and-screencast/

Last modified 16 years ago Last modified on Jul 23, 2008, 10:57:27 AM
Note: See TracWiki for help on using the wiki.
Back to Top