Thursday, 3 July 2008

NewForms Admin - Flatpages

Practical Django Projects (Chapter three), talks about defining an admin interface which is all well and good unless you're using the NewForms Admin branch (which is intended to become part of Release 1.0). So if you're an early adopter or reading this after the big change, you'll be needing to do the following.

The reason I bothered writing this was I couldn't work out how to override the fact that FlatPage had already registered a ModelAdmin (try to register yours throws an error). A pointer from #django on irc and a look at the source code revealed that unregister was the baby you wanted.

from django.contrib import admin
from search.models import SearchKeyword
from django.contrib.flatpages.models import FlatPage

class SearchKeywordInline(admin.TabularInline):
model = SearchKeyword

class FlatPageAdmin(admin.ModelAdmin):
inlines = [
SearchKeywordInline,
]

# We have to unregister it, and then reregister
admin.site.unregister(FlatPage)
admin.site.register(FlatPage, FlatPageAdmin)

3 comments:

Hideki said...

Hi Ian,
I encountered same problem. I tried your code with Django 1.0 Alpha release. It does not work. I got the message "The model FlatPage is not registered". Did you try CMS sample with Alpha release? If so, could you please write solution for Alpha release?
Thanks,
Hideki

Anonymous said...

The problem with this method, is that it overrides the original FlatPageAdmin behavior.

I would suggest that you should derive a new FlatPageAdmin class from the original one (instead of deriving directly from admin.ModelAdmin):

from django.contrib import admin
from search.models import SearchKeyword
from django.contrib.flatpages.models import FlatPage
from django.contrib.flatpages.admin import FlatPageAdmin

class SearchKeywordInlineAdmin(admin.StackedInline):
model = SearchKeyword

class FlatPageNewAdmin(FlatPageAdmin):
inlines = [SearchKeywordInlineAdmin,]

admin.site.unregister(FlatPage)
admin.site.register(FlatPage, FlatPageNewAdmin)

This keeps the show/hide Advance Options behavior of the original FlatPages admin page.

Anonymous said...

Hideki-
I had the same problem. I'm not sure why this solves the problem, but putting this code in its own admin.py file (separate from the original search models.py file) fixed it for me.