如何在django-admin中隐藏特定记录的字段?
如何隐藏djano-admin中特定记录的字段? 例如,如果我有一个模型如何在django-admin中隐藏特定记录的字段?
class Book(models.Model): title = models.CharField(..., null=True)
author = models.CharField(...)
我想隐藏在管理面板的作者与PK记录= 1。我找到了解决方案,
class BookAdmin(admin.ModelAdmin): list_display = ("pk", "get_title_or_nothing")
def get_form(self, request, obj=None, **kwargs):
if obj.pk == "1":
self.exclude = ("author",)
form = super(BookAdmin, self).get_form(request, obj, **kwargs)
return form
它工作得很好,直到我来了从pk == 1的记录返回到其他记录,在这种情况下,表中的所有记录都隐藏了作者字段。
回答:
发生这种情况的原因是因为一旦"author"
字段被附加到self.exclude
后,它就会停留在那里。
对于Django的> = 1.11:
甲更好的地方排除字段动态是ModelAdmin.get_exclude
。它是在Django 1.11中引入的。
def get_exclude(self, request, obj=None, **kwargs): if obj and obj.pk == 1:
# don't modify self.exclude
# instead return it with the extra added field
return self.exclude + ('author',)
return self.exclude
Django的< 1.11:
对于旧版本,你可以做这样的事情:
class BookAdmin(...): exclude = (# common excluded fields)
original_exclude = exclude
def get_form(self, request, obj=None, **kwargs):
if obj and obj.pk == 1:
self.exclude += ('author',)
else:
# change it back to the original_exclude
# for other objects
self.exclude = self.original_exclude
form = super(BookAdmin, self).get_form(request, obj, **kwargs)
return form
以上是 如何在django-admin中隐藏特定记录的字段? 的全部内容, 来源链接: utcz.com/qa/265485.html