How to hide some fields in django-admin?

后端 未结 4 1998
猫巷女王i
猫巷女王i 2021-02-01 00:43
class Book(models.Model):
    title = models.CharField(..., null=True)
    type = models.CharField(...)
    author = models.CharField(...)

I have a sim

4条回答
  •  一整个雨季
    2021-02-01 01:16

    For Django > 1.8 one can directly set the fields to be excluded in admin:

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

    Hidden fields are directly defined in Django's ORM by setting the Field attribute: editable = False

    e.g.

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

    However, setting or changing the model's fields directly may not always be possible or advantegous. In principle the following admin.py setup could work, but won't since exclude is an InlineModelAdmin option.

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

    A solution working at least in Django 1.4 (and likely later version numbers) is:

    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
    

    For the admin list-view of the items, it suffices to simply leave out fields not required: e.g.

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

提交回复
热议问题