Django admin filtering objects by user authenticated

In Django Admin, you can filter objects displayed in the admin interface based on the currently authenticated user. This is particularly useful if you want to limit access to only the objects that the logged-in user is authorized to see. Here’s how you can achieve this:


Steps to Filter Objects by Authenticated User

  1. Override get_queryset in the Admin Class:

    Customize the get_queryset method in your admin class to filter the objects based on the authenticated user.

     

    from django.contrib import admin

    class YourModelAdmin(admin.ModelAdmin):
        def get_queryset(self, request):
            qs = super().get_queryset(request)
            if request.user.is_superuser:
                return qs  # Superusers see all objects
            return qs.filter(user=request.user)  # Filter by authenticated user 

    Register the Admin Class with the Model:

    Associate your admin class with the model.

    return qs.filter(created_by=request.user)
     

    Optional: Restrict Add/Edit Permissions:

    If you also want to restrict the add/edit functionality for users, override the has_add_permission or has_change_permission methods.

    class YourModelAdmin(admin.ModelAdmin):
        def has_add_permission(self, request):
            return request.user.is_staff  # Allow only staff users to add objects

        def has_change_permission(self, request, obj=None):
            if obj is None:
                return True
            return obj.user == request.user  # Allow changes only to the user's objects
     

     

     

Comments