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.
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 .
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With