Permissions in Django Admin

Admin dashboard is one of the Django’s useful feature. Admin dashboard allows super users to create, read, update, delete database objects. The super users have full control over the data. Staff user can login into admin dashboard but can’t access data. In few cases, staff users needs restricted access . Super user can access all data from various in built and third party apps. Here is a screenshot of Super user admin interface after login.

Staff users don’t have access to data.

Allow staff user to access models

Django permissions determines access to models and allowed actions in admin interface. Every model has three permissions. They are <app_label>.add_<model>, <app_label>.change_<model>, <app_label>.delete_<model> allows user to create, edit and delete objects.

API and Admin interface allows assigning permissions to the user.

Staff user can perform various tasks on allowed models after assigning permissions.

Filtering objects in model

Conference management system hosts many conferences in a single instance. Each conference has different set of moderators. System allows only conference specific moderators to access the data. To achieve the functionality, Django provides an option to override queryset. Admin requires custom implementation of get_queryset method. Here is how a sample code looks like.

class ConferenceAdmin(AuditAdmin):
    list_display = ('name', 'slug', 'start_date', 'end_date', 'status') + AuditAdmin.list_display
    prepopulated_fields = {'slug': ('name',), }

    def get_queryset(self, request):
        qs = super(ConferenceAdmin, self).get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(moderators=request.user)

class ConferenceProposalReviewerAdmin(AuditAdmin, SimpleHistoryAdmin):
    list_display = ('conference', 'reviewer', 'active') + AuditAdmin.list_display
    list_filter = ('conference',)

    def get_queryset(self, request):
        qs = super(ConferenceProposalReviewerAdmin, self).get_queryset(
        request)
        if request.user.is_superuser:
            return qs
        moderators = service.list_conference_moderator(user=request.user)
        return qs.filter(conference__in=[m.conference for m in moderators])

Filtered moderator objects for staff user.

Unfiltered moderator objects for superusers.

Note the difference in total number of objects (23, 30) in the view.

See also

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

Powered by Buttondown.