Skip to content

Instantly share code, notes, and snippets.

@nailor
Created November 16, 2011 15:52
Show Gist options
  • Save nailor/1370436 to your computer and use it in GitHub Desktop.
Save nailor/1370436 to your computer and use it in GitHub Desktop.
# Adding a semi-dynamic field to Django ModelAdmin
#
# Motivation behind this is to see if django.conf.settings contains a
# setting of some type. I know this could be done with a factory too.
#
# django.forms.Form allows adding extra fields to forms initialization
# time by modifying self.fields dict in __init__. However, ModelAdmin
# only looks at the *class* of the form, not the instance created from
# it, to determine the fields it should draw in the admin interface.
#
# Also: using fields or fieldsets is not an option, as they're are
# checked against the same class's fields, thus raising an exception
# upon init
#
# Basically: adding to self.fields in a form used by ModelAdmin is a
# no-op in Django. I came up with this solution:
from django.contrib import admin
from django.conf import settings
from django import forms
from myapp.models import MyModel
class DynamicFormType(forms.ModelForm.__metaclass__):
# Akward superclass due to the __all__ variable in django.forms :(
def __init__(cls, name, bases, dct):
super(DynamicFormType, cls).__init__(name, bases, dct)
if getattr(settings, 'APPEND_DYNAMIC_FIELD', False):
cls.base_fields['dynamic_field'] = forms.CharField()
class MyCustomForm(forms.ModelForm):
__metaclass__ = DynamicFormType
model = MyModel
somefield = forms.CharField()
class MyAdmin(admin.ModelAdmin):
form = MyCustomForm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment