Manuel Santi
Manuel Santi

Reputation: 1132

Django admin hide fields and block edit/delete data

In my django project i have to achieve 3 tasks in my admin section:

  1. Remove 2 fields in add template
  2. Remove the possibility to Delete a record
  3. Remove the possibility to Edit a record

My model:

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))

I try this in 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'))

..but nothing appen! No fields hidden, deletion and modification always active. How can i achieve my 3 goals?

thanks in advance

Upvotes: 0

Views: 1691

Answers (1)

Messaoud Zahi
Messaoud Zahi

Reputation: 1232

Remove 2 fields in add template

You can achieve this by adding editable = False to status and docs fields like this:

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

Remove the possibility to Delete a record Remove the possibility to Edit a record

In your admin class add:

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

Your suite_libsAdmin class will be like this:

class suite_libsAdmin(admin.ModelAdmin):
    actions = None
    list_display_links = None

for more informations consult the documentation:

Disabling all actions for a particular ModelAdmin

Field.editable

Upvotes: 3

Related Questions