老师你好,我用的django3.1,我想后台的admin在打开一个表单的时候,赋给一个计算来的初始值
网上查到可以在admin.py文件中,使用
formfield_for_dbfield来实现
class Trading_recordAdmin(admin.ModelAdmin):
def formfield_for_dbfield(self, db_field, request, **kwargs):
# field = super(Trading_recordAdmin,self).formfield_for_dbfield(db_field, request, **kwargs)
if db_field.name == "r_amount":
self.formfield_overrides[r_amount] = 11
return super(Trading_recordAdmin,self).formfield_for_dbfield(db_field, request, **kwargs)
'''设置列表可显示的字段'''
list_display = ('release_time', 'addtime', 'amount', 'category',)
追踪到formfield_for_dbfield里看到源码中说使用formfield_overrides重写字段值,不知道理解的对不对
# If we've got overrides for the formfield defined, use 'em. **kwargs
# passed to formfield_for_dbfield override the defaults.
for klass in db_field.__class__.mro():
if klass in self.formfield_overrides:
kwargs = {**copy.deepcopy(self.formfield_overrides[klass]), **kwargs}
return db_field.formfield(**kwargs)
我想要一个模型,在admin表单显示的时候,其中一个字段在表单上显示的值,是通过其它字段计算来的,这个我应该怎么实现呢