[Django]-Django 1.7, dynamic admin form

3👍

Django > 1.4 introduced a change that causes this breakage. Basically get_fieldsets is called before the form factory, and then the factory complains about the extra field you introduce in get_fieldsets. Luckily get_fieldsets is called more than once, presenting opportunity to subvert the flow. My solution is to add a marker attribute to the request while it passes through the form mechanism:

def get_fieldsets(self, request, obj=None):
    fieldsets = super(DeviceAdmin, self).get_fieldsets(request, obj)
    if hasattr(request, "_gfs_marker"):
        fieldsets[0][1]['fields'] += ('foo',)
    setattr(request, "_gfs_marker", 1)
    return fieldsets

0👍

If it is just the field name visible to the user that you want to alter (the internal field name will not be visible anyway), you could use a class factory:

def get_MyDeviceAdminForm(field_name):
    class MyDeviceAdminForm(forms.ModelForm):
        my_new_field_internal = forms.CharField(label=field_name)
        class Meta:
            model = InfoLog
    return MyDeviceAdminForm
class DeviceAdmin(admin.ModelAdmin):
    form = get_MyDeviceAdminForm("Verbose name of the new field")

This works in Django 1.6.

Leave a comment