Django管理员隐藏字段并阻止编辑/删除数据

时间:2018-10-04 09:54:48

标签: django django-models orm django-admin

在我的django项目中,我必须在管理部分中完成3个任务:

  1. 删除添加模板中的2个字段
  2. 消除删除记录的可能性
  3. 消除了编辑记录的可能性

我的模特:

class suite_libs(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, blank=True)
    descr = models.TextField(null=True, blank=True)
    docs = models.TextField(null=True, blank=True)
    lib_name = models.CharField(max_length=255, blank=True)
    status = models.CharField(max_length=10, default='APPROVAL')
    f_lib = models.FileField(upload_to='libs/', blank=True)
    notes = models.TextField(null=True, blank=True)

    class Meta:
        verbose_name = 'LIBRARIES'
        verbose_name_plural = 'LIBRARIES'
        ordering = ('name', 'lib_name', 'status',)

    def __str__(self):
        return '%s -> %s (%s)' % (
            str(self.name), str(self.lib_name), str(self.status))

我在admin.py中尝试了此操作

class suite_libsAdmin(admin.ModelAdmin):

    #1-For hide two fields in add
    def get_form(self, request, obj=None, **kwargs):
        if obj.type == "1":
            self.exclude = ("status", "docs" )
        form = super(suite_libsAdmin, self).get_form(request, obj, **kwargs)
        return form

    #2-For block deletion
    def get_actions(self, request):
        actions = super().get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions

    #3-For block editing   
    def change_view(self, request, obj=None):
        from django.core.urlresolvers import reverse
        from django.http import HttpResponseRedirect
        return HttpResponseRedirect(reverse('admin:myapp_mymodel_changelist'))

..但没有任何反应!没有隐藏,删除和修改的字段始终处于活动状态。 我如何实现我的3个目标?

预先感谢

1 个答案:

答案 0 :(得分:1)

  

删除添加模板中的2个字段

您可以通过将0 'before' 1 'after' { _id: 5bb5d47bbfa2d3ea077c37a6, name: 'Jeff' } 2 'before' 3 'after' { _id: 5bb5d483bfa2d3ea077c37a8, name: 'Jerald' } 4 'before' 5 'after' { _id: 5bb5d493bfa2d3ea077c37aa, name: 'Somebody' } 6 'before' 7 'after' { _id: 5bb5df8dbfa2d3ea077c39c8, name: 'Waddup' } 8 'before' done 添加到editable = Falsestatus字段来实现此目的,

docs
  

消除删除记录的可能性   消除了编辑记录的可能性

在您的管理类中添加:

....
docs = models.TextField(null=True, blank=True, editable= False)
status = models.CharField(max_length=10, default='APPROVAL', editable= False)
....

您的suite_libsAdmin类将如下所示:

actions = None # to disable delete button
list_display_links = None # to disable edit link

有关更多信息,请参阅文档:

Disabling all actions for a particular ModelAdmin

Field.editable