Search code examples
djangodjango-modelsmonkeypatching

Add functionality to Django FlatPages without changing the original Django App


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


Solution

  • 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.