如何在Django Admin中使用can_add_related

时间:2012-04-30 01:47:50

标签: python django django-admin

我在这里读到了关于can_add_related的功能:https://code.djangoproject.com/ticket/9071

我尝试过这样使用它:

def get_form(self, request, obj=None, **kwargs):
    self.fields['person'].can_add_related = False
    return super(OperationAdmin, self).get_form(request, obj, **kwargs)

但这引发了一个TypeError,我不知道如何解决这个问题。

有人能指出我正确的方向吗?

谢谢。

4 个答案:

答案 0 :(得分:11)

这可能是迟到的。但是对于其他观众的参考,

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

答案 1 :(得分:2)

can_add_related似乎是an attribute on the widget,而不是字段,所以请尝试:

self.fields['person'].widget.can_add_related = False

答案 2 :(得分:0)

另一种方法,在实例化表单之前,需要更改窗口小部件选项:

class MyAdmin(django.contrib.admin.ModelAdmin):

    def formfield_for_dbfield(self, *args, **kwargs):
        formfield = super().formfield_for_dbfield(*args, **kwargs)
        if hasattr(formfield, "widget"):
            formfield.widget.can_add_related = False
            formfield.widget.can_delete_related = False
            formfield.widget.can_change_related = False
        else:
            pass  # this relation doesn't have an admin page to add/delete/change

        return formfield

答案 3 :(得分:0)

另一种方法,如果您要定义内联模型并在您的管理员中使用它,则使用 overwrite the get_formset 方法:

from django.contrib import admin


class MyModelInline(admin.TabularInline):
    model = MyModel
    extra = 0
    min_num = 1
    max_num = 10
    fields = [
        'some_field'
    ]

    def get_formset(self, request, obj=None, **kwargs):
        fs = super().get_formset(request, obj, **kwargs)
        fs.form.base_fields['some_field'].widget.can_add_related = False
        fs.form.base_fields['some_field'].widget.can_change_related = False
        fs.form.base_fields['some_field'].widget.can_delete_related = False
        return fs