问题
I would like to add a field to the Django FlatPage database model, but I do not really know how to extend this without editing the original application.
What I want to do is to add the following field to the model:
from django.db import models
from django.contrib.flatpages.models import FlatPage as FlatPageOld
class FlatPage(FlatPageOld):
order = models.PositiveIntegerField(unique=True)
How do I get to add this to the FlatPage model?
Thanks in advance
回答1:
Your approach is fine - you just don't see the result because the old flatpage model is registered in the admin and the new one isn't. Here's what you might do in your new app's admin.py (using less ambiguous naming than what you've got above):
from django.contrib import admin
from django.contrib.flatpages.admin import FlatPageAdmin
from django.contrib.flatpages.forms import FlatpageForm
from django.contrib.flatpages.models import FlatPage
from models import ExtendedFlatPage
class ExtendedFlatPageForm(FlatpageForm):
class Meta:
model = ExtendedFlatPage
class ExtendedFlatPageAdmin(FlatPageAdmin):
form = ExtendedFlatPageForm
fieldsets = (
(None, {'fields': ('url', 'title', 'content', 'sites', 'order')}),
)
admin.site.unregister(FlatPage)
admin.site.register(ExtendedFlatPage, ExtendedFlatPageAdmin)
Obviously there are a few things going on here, but most importantly the FlatPage model is being unregistered and the ExtendedFlatPage model is being registered in its place.
回答2:
And the method in your post doesn't work because... ?
If for some reason you really need to fiddle with the builtin FlatPage class and edit it dynamically, you can hook to the class_prepared signal:
http://docs.djangoproject.com/en/dev/ref/signals/#class-prepared
Edit
Here's how you'd do it with a class_prepared:
from django.db.models.signals import class_prepared
from django.db import models
def alter_flatpages(sender, **kwargs):
if sender.__module__ == 'django.contrib.flatpages.models' and sender.__name__ == 'FlatPage':
order = models.IntegerField()
order.contribute_to_class(sender, 'order')
class_prepared.connect(alter_flatpages)
Put this in, say, 'signals.py' in the same directory as your settings.py, and add 'signals' to the top (this is important, to make sure the signal handler gets installed in time) of the INSTALLED_APPS list .
However, this still won't get the field displayed in Admin, because there's a custom ModelAdmin class for FlatPages which explicitely lists the fields. So after it gets registered in the flatpages app, you'd need to unregister it somewhere (admin.site.unregister) and register a ModelAdmin of your own.
来源:https://stackoverflow.com/questions/1021487/add-functionality-to-django-flatpages-without-changing-the-original-django-app