Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin : show records for respective user only

I have a simple model, say Resources. And I have fewer than 20 users and model admin serves the purpose to record requests.

Problem is that all users can see all records in model admin site.

Can this behaviour be changed to only show records created by same user only ?

Thank you in anticipation.

like image 322
user1619524 Avatar asked May 24 '17 14:05

user1619524


People also ask

How do I restrict access to parts of Django admin?

Django admin allows access to users marked as is_staff=True . To disable a user from being able to access the admin, you should set is_staff=False . This holds true even if the user is a superuser. is_superuser=True .

What is List_display Django?

list_display. Set list_display to control which fields are displayed on the change list page of the admin. Example: list_display = ('first_name', 'last_name') If you don't set list_display , the admin site will display a single column that displays the __str__() representation of each object.

Can we customize Django admin panel?

We have a lot of tools in Django to customize it to our own needs and in this article, we'll learn how to customize the admin interface and add multiple features: Let's setup your project, add models into models.py and register your models.


2 Answers

The django doc has an example that does almost exactly what you want:

https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_queryset

The idea is to override the get_queryset() method in the model admin view:

# admin.py
from django.contrib import admin

class YourModelAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        qs = super(MyModelAdmin, self).get_queryset(request)
        return qs.filter(author=request.user)

admin.site.register(YourModel, YourModelAdmin)

You can adapt the queryset filter to even more specific needs at will.

like image 78
mimo Avatar answered Sep 18 '22 19:09

mimo


UPDATE 2020: Anyone who is curious as to what is the author field, then that is established in the models.py file of your app. For the admin.py part, you can visit the docs.

Step 1:

Make sure in your permissions you give access to the apps you want your users to have CRUD functionality over.

Step 2:

Admin.py

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

Models.py

from django.contrib.auth import get_user_model

class Lecture(models.Model):
    author = models.ForeignKey(get_user_model(), null=True, on_delete=models.CASCADE)
like image 31
Azmol Avatar answered Sep 17 '22 19:09

Azmol