如何在django-admin中隐藏一些字段?

iyzzxitl  于 2023-01-31  发布在  Go
关注(0)|答案(7)|浏览(251)
class Book(models.Model):
    title = models.CharField(..., null=True)
    type = models.CharField(...)
    author = models.CharField(...)

我在models.py中有一个简单的类。在admin中,当保存的图书类型为1时,我想隐藏图书的标题(在图书详细信息表单中)。如何以最简单的方式做到这一点?

kx7yvsdv

kx7yvsdv1#

对于Django〉1.8,可以直接在admin中设置要排除的字段

class PostCodesAdmin(admin.ModelAdmin):
      exclude = ('pcname',)

隐藏字段可以通过设置Field属性直接在Django的ORM中定义:editable = False
例如:

class PostCodes(models.Model):
  gisid  = models.IntegerField(primary_key=True)
  pcname = models.CharField(max_length=32, db_index=True, editable=False)
  ...

然而,直接设置或更改模型的字段并不总是可行的或有利的。原则上,下面的admin.py设置可以工作,但不会,因为exclude是一个InlineModelAdmin选项。

class PostCodesAdmin(admin.ModelAdmin):
     exclude = ('pcname',)
....

一个至少在Django 1.4(以及更高版本号)中有效的解决方案是:

class PostCodesAdmin(admin.ModelAdmin):
  def get_form(self, request, obj=None, **kwargs):
      form = super(PostCodesAdmin, self).get_form(request, obj, **kwargs)
      del form.base_fields['enable_comments'] 
      return form

对于项目的管理列表视图,只需省略不需要的字段即可:例如:

class PostCodesAdmin(admin.ModelAdmin):
  list_display = ('id', 'gisid', 'title', )
q35jwt9p

q35jwt9p2#

您将在模块中创建admin.py(可能是book

class BookAdmin(admin.ModelAdmin):
    list_display = ("pk", "get_title_or_nothing")

Book课程中:

class Book:
    ...
    def get_title_or_nothing(self):
        if self.type == WEIRD_TYPE:
            return ""
        return self.title

更新日期:

class BookAdmin(admin.ModelAdmin):
    list_display = ("pk", "get_title_or_nothing")

    def get_form(self, request, obj=None, **kwargs):
        if obj.type == "1":
            self.exclude = ("title", )
        form = super(BookAdmin, self).get_form(request, obj, **kwargs)
        return form
d6kp6zgx

d6kp6zgx3#

我试图覆盖get_form()函数,但当我切换到不同的记录时,发生了一些混淆错误。我发现有一个get_exclude()函数可以覆盖。
use:

class BookAdmin(admin.ModelAdmin):
    def get_exclude(self, request, obj=None):
        if obj and obj.type == "1":
            # When you create new data the obj is None
            return ("title", )
        return super().get_exclude(request, obj)
ryhaxcpt

ryhaxcpt4#

class BookAdmin(admin.ModelAdmin):
    exclude = ("fieldname",)  # hide fields which you want
guicsvcw

guicsvcw5#

关于“洛伦兹”先生的回答
在Django 2.1中,我发现如果字段已经通过fields =指定,exclude就不起作用。
在这种情况下,您可以使用

self.fields.remove('title')

字段必须定义为list []才能使其生效

zf9nrax1

zf9nrax16#

如果您希望保留表单中的值(例如,根据请求设置一个值,即user)并隐藏字段,则可以将小部件更改为forms.HiddenInput()

from django import forms

...

    def get_form(self, request, obj=None, **kwargs):
        """Set defaults based on request user"""
        # update user field with logged user as default
        form = super().get_form(request, obj, **kwargs)
        form.base_fields["user"].initial = request.user.id
        form.base_fields["user"].widget = forms.HiddenInput()
        return form
6tqwzwtp

6tqwzwtp7#

下面是一个工作示例

class BookAdmin(admin.ModelAdmin):
    def get_fieldsets(self, request, obj):
        if obj is None:
            return [
                (
                    None,
                    {'fields': ('type', 'description',)}
                )
            ]
        elif request.user.is_superuser:
            return [
                (
                    None,
                    {'fields': ('type', 'status', 'author', 'store', 'description',)}
                )
            ]
        else:
            return [
                (
                    None,
                    {'fields': ('type', 'date', 'author', 'store',)}
                )
            ]

相关问题