Dynamic fields in Django Admin

后端 未结 9 1485
失恋的感觉
失恋的感觉 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:44

    Maybe I am a bit late... However, I am using Django 3.0 and also wanted to dynamically ad some custom fields to the form, depending on the request.

    I end up with a solution similar to the one described by @tehfink combined with @little_birdie.

    However, just updating self.form.declared_fields as suggested didn't help. The result of this procedure is, that the list of custom fields defined in self.form.declared_fields always grows from request to request.

    I solved this by initialising this dictionary first:

    class ModelAdminGetCustomFieldsMixin(object):
        def get_fields(self, request, obj=None):
            fields = super().get_fields(request, obj=None)
            self.form.declared_fields = {}
            if obj:
                for custom_attribute in custom_attribute_list:
                    self.form.declared_fields.update({custom_attribute.name: custom_attribute.field})
            return fields
    

    where custom_attribute.field is a form field instance.

    Additionally, it was required to define a ModelForm, wherein during initialisation the custom fields have been added dynamically as well:

    class SomeModelForm(forms.ModelForm):
    
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            for custom_attribute in custom_attribute_list:
                self.fields[custom_attribute.name] = custom_attribute.field
    
    

    and use this ModelForm in the ModelAdmin.

    Afterwards, the newly defined attributes can be used in, e.g., a fieldset.

提交回复
热议问题