Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic forms in django-admin

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.

like image 931
inc0 Avatar asked Nov 27 '10 11:11

inc0


1 Answers

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.

like image 191
inc0 Avatar answered Sep 24 '22 23:09

inc0