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

标签 python django django-forms django-admin

我在我的 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/

相关文章:

python - 如何递归替换也是键的字典中的值,直到值中没有键为止?

python - 如何将具有 dtype 的列作为对象转换为 Pandas Dataframe 中的字符串

python - 选择最大值时从列表中返回随机值并且具有 2 个相同的最大值

django - 设置模型的 __unicode__ 以在管理中显示 html 标签

Django 'QuerySet' 对象没有使用 modelform 的属性 'split'

python - 如何将url中捕获的值传递到html页面?

python - 生成长度为32的随机二进制字符串

python - 如何让 python 模块异步运行并接收来自其他模块的调用?

javascript - tail -f 在浏览器中

python - 默认的 Django 管理表单和 FormWizard