Eerik Sven Puudist
Eerik Sven Puudist

Reputation: 2346

Django admin restrict access to list view

Here is a model:

class Person(models.Model):
    name= models.CharField(max_length=100, blank=True)
    identity_number= models.IntegerField(unique=True)

name field should be public, identity_number, however, should be confidential.

I would like to show name in admin list view and both fields in change form view.

I would like to create one group of users, who can access only list view and another group of users, who can access both views.

This means that the first group of users should not see links to change form and if they try to access the change form page directly, 403 (or something like that) should be returned. How to achieve this?

Upvotes: 1

Views: 1546

Answers (1)

rollingthedice
rollingthedice

Reputation: 1125

If by list view you mean the changelist_view then you can do:

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('name', 'identity_number', )

    def changelist_view(self, request, extra_context=None):
        if request.user.groups.filter(name='your_group_name').exists():
            self.list_display = ('name', )
            # if you dont want any links to the change_form
            self.list_display_links = None
        return super(MyModelAdmin, self).changelist_view(request, extra_context)

Upvotes: 4

Related Questions