Django管理内联仅在更改对象时显示

2024-05-15 00:22:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个UserProfile,它有许多必需的(不是null而是空白)字段,在添加user时我尽量不显示它。你知道吗

我尝试了多种方法,例如:

def get_formsets_with_inlines(self, request, obj=None):
    if not obj:
        return []
    return super().get_formsets_with_inlines(request, obj)

但是在保存User之后,django会产生一个错误,即UserProfile中的字段不能为空。你知道吗

你知道怎么做吗?你知道吗


Tags: 方法selfnoneobjgetreturnrequestdef
1条回答
网友
1楼 · 发布于 2024-05-15 00:22:49

ModelAdmin为条件内联线提供了一个方法get_inline_instances。你知道吗

从文档中:

The get_inline_instances method is given the HttpRequest and the obj being edited (or None on an add form) and is expected to return a list or tuple of InlineModelAdmin objects.

例如:

class MyModelAdmin(admin.ModelAdmin):
    inlines = (MyInline,)

    def get_inline_instances(self, request, obj=None):
        return [inline(self.model, self.admin_site) for inline in self.inlines]

在这里您可以检查obj是否存在。你知道吗

文件中有一点很重要:

If you override this method, make sure that the returned inlines are instances of the classes defined in inlines or you might encounter a “Bad Request” error when adding related objects.

相关问题 更多 >

    热门问题