Search code examples
djangodjango-admindjango-querysetdjango-admin-filtersdjango-admin-tools

How to allow a user to view data that is added only by him Django Admin


I have a Django application, where the user with restricted access registers a new post in Django admin.

This user can only see in the table to register, update and delete the posts inserted by him, and can not view the posts entered by another user, all within Admin Django, unless it has super user status.

I've tried to create "def queryset" in my "NoticiaAdmin (admin.ModelAdmin)" class, and unfortunately I do not know what I'm doing wrong, I can not solve this problem.

Here is my queryset function...

def queryset(self, request): 
    if request.user.is_superuser: 
        qs = self.model._default_manager.get_query_set() 
    else: 
        qs = self.model._default_manager.get_query_set().filter(user=request.user) 
    ordering = self.ordering or () 
    if ordering: 
        qs = qs.order_by(*ordering)     
    return qs 

I hope that I have clarified my doubts about the problem and I will be very grateful to anyone who can help me.


Solution

  • You may need to call super() on the method in the ModelAdminclass.

    Maybe try something like this,

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