我已在get_form()
课程中覆盖ModelAdmin
:
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'
为什么会这样?如果对超级get_form()
的调用设置了表单上的fields
属性吗?如果我弄错了,我如何访问ModelAdmin
类中表单上的字段?
答案 0 :(得分:2)
get_form
返回class而不是实例,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.
"""
更新
我需要拦截表单字段创建,而不是视图。我需要 更改字段的值,而不是弄乱模板的上下文。我没有 认为add_view()是适合它的地方。
我认为您可以通过覆盖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