11

我在这里阅读了有关 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

4 回答 4

19

这可能来晚了。但供其他观众参考,

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
于 2013-06-27T16:26:10.537 回答
4

can_add_related似乎是小部件上的一个属性,而不是字段,所以试试:

self.fields['person'].widget.can_add_related = False
于 2012-04-30T02:03:56.383 回答
1

替代方法,通过更改小部件选项 *before* 实例化表单:

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
于 2019-11-22T09:43:03.193 回答
1

另一种方法,如果您要定义一个内联模型并在您的管理员中使用它,将覆盖 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
于 2021-06-07T14:49:41.143 回答