gpt4 book ai didi

python - Django ModelAdmin get_form() 没有设置字段属性

转载 作者:行者123 更新时间:2023-11-28 17:42:20 26 4
gpt4 key购买 nike

我在我的 ModelAdmin 类中覆盖了 get_form():

def get_form(self, request, obj=None, **kwargs):
form = super(ModelAdmin, self).get_form(request, obj, **kwargs)

现在,如果我添加这一行:

print form.fields

我得到一个:

AttributeError: type object 'FilerImageForm' has no attribute 'fields'

为什么会这样?调用 super get_form() 是否应该在表单上设置 fields 属性?如果我弄错了,如何访问 ModelAdmin 类中的表单字段?

最佳答案

get_form 返回类而不是实例,fields 属性是实例属性。因此,您必须在访问字段之前实例化表单。

来自 django/contrib/admin/options.py 的定义:

def get_form(self, request, obj=None, **kwargs):
"""
Returns a Form class for use in the admin add view. This is used by
add_view and change_view.
"""

更新:

I need to intercept form field creation, not the view. I need to change a field's value, not mess with a template's context. I don't think add_view() is the appropriate place for this.

我认为你可以通过覆盖 formfield_for_dbfield 方法来做到这一点:

def formfield_for_dbfield(self, db_field, **kwargs):
"""
Hook for specifying the form Field instance for a given database Field
instance.

If kwargs are given, they're passed to the form Field's constructor.
"""

formfield = super(MyModelAdmin, self).formfield_for_dbfield(db_field, **kwargs)

if db_field.name == "field_you_are_looking_for":
# change formfield somehow here
# (or above, by passing modified kwargs in 'super' call)

return formfield

关于python - Django ModelAdmin get_form() 没有设置字段属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22482591/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com