Django - How to prepopulate admin form fields

前端 未结 7 1264
梦谈多话
梦谈多话 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:13

    Django's built-in prepopulated_fields functionality is hardcoded to slugify, it can't really be used for more general purposes.

    You'll need to write your own Javascript function to do the prepopulating. The best way to get it included in the admin page is to include it in the inner Media class of a custom Form or Widget. You'll then need to customize your ModelAdmin subclass to use the custom form or widget. Last, you'll need to render some inline Javascript along with each prepopulated field to register the onchange handler and tell it which other field to populate from; I would render this via the custom Widget. To make it nice and declarative you could use a custom ModelAdmin attribute (similar to prepopulated_fields), and override ModelAdmin.formfield_for_dbfield to create the widget and pass in the information about what field it should prepopulate from.

    This kind of admin hacking is almost always possible, but (as you can tell from this convoluted summary) rarely simple, especially if you're making an effort to keep your code nicely encapsulated.

提交回复
热议问题