Dynamic fields in Django Admin

后端 未结 9 1467
失恋的感觉
失恋的感觉 2020-12-05 05:18

I want to have additional fields regarding value of one field. Therefor I build a custom admin form to add some new fields.

Related to the blogpost of jacobian 1 thi

9条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 05:31

    This works for adding dynamic fields in Django 1.9.3, using just a ModelAdmin class (no ModelForm) and by overriding get_fields. I don't know yet how robust it is:

    class MyModelAdmin(admin.ModelAdmin):
    
        fields = [('title','status', ), 'description', 'contact_person',]
        exclude = ['material']
    
        def get_fields(self, request, obj=None):
            gf = super(MyModelAdmin, self).get_fields(request, obj)
    
            new_dynamic_fields = [
                ('test1', forms.CharField()),
                ('test2', forms.ModelMultipleChoiceField(MyModel.objects.all(), widget=forms.CheckboxSelectMultiple)),
            ]
    
            #without updating get_fields, the admin form will display w/o any new fields
            #without updating base_fields or declared_fields, django will throw an error: django.core.exceptions.FieldError: Unknown field(s) (test) specified for MyModel. Check fields/fieldsets/exclude attributes of class MyModelAdmin.
    
            for f in new_dynamic_fields:
                #`gf.append(f[0])` results in multiple instances of the new fields
                gf = gf + [f[0]]
                #updating base_fields seems to have the same effect
                self.form.declared_fields.update({f[0]:f[1]})
            return gf
    

提交回复
热议问题