Django Admin - get_form覆盖

时间:2017-04-13 21:50:46

标签: django django-admin

我想在admin.py中覆盖get_form方法。我写了这段代码:

def get_form(self, request, obj=None, **kwargs):
    form = super(InactiveSiteAdmin, self).get_form(request, obj, **kwargs)
    form.base_fields['category'].widget.can_add_related = False
    form.base_fields['subcategory'].widget.can_add_related = False
    form.base_fields['category1'].widget.can_add_related = False
    ...
    ...
    form.base_fields['category'].widget.can_change_related = False
    return form

是否可以覆盖一行中的所有字段?:

form.base_fields[ALL_FIELDS].widget.can_add_related = False

1 个答案:

答案 0 :(得分:1)

看看循环是否有效,例如:

def get_form(self, request, obj=None, **kwargs):
    form = super(InactiveSiteAdmin, self).get_form(request, obj, **kwargs)
    for field in form.base_fields.keys():
        form.base_fields[field].widget.can_add_related = False
    return form