msgbartop
by Brian Neal
msgbarbottom

05 Mar 09 Custom Admin View Gotcha in Django 1.1

I ran into something that took a few hours to sort out, so I thought I would write it up here in case it would help some other poor dope out.

My goal is to create a custom admin view. I noticed that the Django docs had been updated recently, documenting a new member function called get_urls() on the ModelAdmin class. The docs are kind of sketchy right now, but I gathered that this was the new way to add custom admin views for a model. However, before you can use this new feature, you have to cut over to the new scheme of hooking the contrib.admin site into your project. This is what took me a few hours to figure out, as I hadn’t noticed this change in the docs.

This is how I had my URLConf in my Django 1.0 project:

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

After updating my working copy of Django trunk, this is what my URLConf needed to look like to use the new admin get_urls() scheme:

urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
# ...

All the changes are on line 2. Notice, there are two changes you have to make:

  1. The admin.site.root function is deprecated. You should now use include(admin.site.urls).
  2. The regular expression has changed subtly. Notice that the capturing of the part of the URL after ‘admin/’ is no longer needed. I didn’t notice this right away, and trust me, it does weird things if you leave it in. :)

After finally figuring these two things out, I am happy to report that the get_urls() function on my ModelAdmin class worked as I expected. For example, if I use the regular expression ‘^my_view/$’ for my custom admin view, the view will be located at /admin/appname/modelname/my_view. This isn’t quite made crystal clear in the Django docs.

Now I am poised to add a custom admin view on my Google Calendar application. Stay tuned for more on that.

Tags: ,