Django - How to prepopulate admin form fields

前端 未结 7 1255
梦谈多话
梦谈多话 2020-12-08 14:54

I know that you can prepopulate admin form fields based on other fields. For example, I have a slug field that is automatically populated based on the title field.

H

7条回答
  •  隐瞒了意图╮
    2020-12-08 15:09

    I tried a few of these answers and none of them worked. I simply wanted to prepulate a field with another field from a related model. Taking this answer as a starting point, I finally tried to manipulate the model instance object (here obj) directly and it worked for me.

    class MyModelAdmin(models.ModelAdmin):
    
        def get_form(self, request, obj=None, **kwargs):
            form = super(MyModelAdmin, self).get_form(request, obj, **kwargs)
            if not obj.some_model_field:
                obj.some_model_field = obj.related_model.prepopulating_model_field
    
            return form
    

提交回复
热议问题