8

I want to make admin add-form dynamic. I want to add few formfields depending on setting in related object.

I have something like this:

class ClassifiedsAdminForm(forms.ModelForm):


  def __init__(self,*args, **kwargs):
     super(ClassifiedsAdminForm, self).__init__(*args, **kwargs)
     self.fields['testujemy'] = forms.CharField(label = "test")

And in admin.py:

class ClassifiedAdmin(admin.ModelAdmin):
     def get_form(self, request, obj=None, **kwargs):
         return ClassifiedsAdminForm

As you can see, I want to add "testujemy" CharField to admin add-form and change-form. However, this way doesnt work. Is there any way to add field in init? It is working in normal view.

inc0
  • 215
  • 2
  • 8

1 Answers1

8

I've managed to do it using type().

class ClassifiedAdmin(admin.ModelAdmin):

 def get_form(self, request, obj=None, **kwargs):

    adminform = ClassifiedsAdminForm()
    fields = adminform.getNewFields()

    form = type('ClassifiedsAdminForm', (forms.ModelForm,), fields)

    return form

Hope it will help someone.

inc0
  • 215
  • 2
  • 8
  • Thanks, great work, saved me a lot of time figuring it out myself :) – fijter Jul 19 '11 at 11:30
  • This still greatly confuses me. I would expect to be able to simply specify the form class in the ModelAdmin class definition. I appreciate your adding this answer, though; there are a couple other SO questions that seem equivalent but remain un- or incompletely answered. – rych Aug 29 '11 at 05:26
  • If this doesn't make sense to you, read this: http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python until it does. Django uses metaclasses heavily internally, particularly with Models and Forms – B Robster Mar 13 '12 at 03:55