5

So, I have a ModelAdmin that I need to add extra fields to. These fields do not exist on the model, but will be dynamically added to a custom ModelForm through the init method, and logic inside clean will handle the returned data on save.

I can't seem to find any solid information related to adding custom non-model fields to a ModelAdmin form. The closest I have come is by overriding get_fields on the ModelAdmin class and updating self.form.declared_fields with the new fields I'd like to add.

This just doesn't feel very clean to me and I was curious if there was a better way to add new fields to a ModelAdmin dynamically?

James Foley
  • 129
  • 1
  • 9
  • https://stackoverflow.com/questions/8007095/dynamic-fields-in-django-admin – ndpu Apr 30 '18 at 12:33
  • This is more or less what I am using currently to display fields, but it doesn't seem overly clean. I assumed there was a cleaner simpler way of doing it. – James Foley Apr 30 '18 at 15:10
  • Possible duplicate of [django admin - add custom form fields that are not part of the model](https://stackoverflow.com/questions/17948018/django-admin-add-custom-form-fields-that-are-not-part-of-the-model) – Satendra Apr 30 '18 at 15:48
  • Fields need to be defined dynamically and cannot belong to the form statically. The custom fields are loaded from a list elsewhere. – James Foley Apr 30 '18 at 16:31

1 Answers1

-1

You can also use this way to add fields not in the models.py

in admin.py:::

from django.utils.translation import gettext as _

class TrialAdmin(admin.ModelAdmin):
    fields = (..., 'non_model_field',...,)

    def non_model_field(self, instance):
    # this method name should be same as new field name defied above in fields.
        # [what u need to do here]

    non_model_field.short_description = _("non_model_field")
    #This value 'short_description' defines what the field name is shown as in admin similar to 'verbose_name' in models.

admin.site.register(..., TrialAdmin)