Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django admin site - display model objects created by request.user only

I have simple blog app which have author=models.ForeignKey(User, editable=False) field. Blog posts are created from django admin site, and I use save_model to get author which is request.user.

Now I want that user (is_staff) can see only his own posts, when he browse model posts. But by default all blog posts are displayed, so how can I hide blog posts created by other users? Of course superusers need to see all of them.

like image 618
Goran Avatar asked Oct 21 '25 04:10

Goran


2 Answers

Override the get_queryset method on the ModelAdmin subclass. The documentation has an example of exactly what you're asking for: displaying only objects related to the current user.

like image 100
Daniel Roseman Avatar answered Oct 23 '25 20:10

Daniel Roseman


In case anyone is lazy. Here's a sample code I use. So first you create a QuerySet Manager, I usually have mine in models.py, which does something like this (in this case I'm calling the model Blog):

class BlogManager(models.Manager):
    def get_queryset(self, request):
        query = Blog.objects.filter(author=request.user)
        if request.user.is_superuser:
            query = UserProfile.objects.all()
        return query

Make sure your admin.py then has this:

    def get_queryset(self, request):
        queryset = BlogManager.get_queryset(self, request)
        return queryset

So it might look like:

class BlogAdmin(admin.ModelAdmin):
   #add any other code here

   #Using that queryset manager created before
   def get_queryset(self, request):
        queryset = BlogManager.get_queryset(self, request)
        return queryset
admin.site.register(BlogAdmin)

Hope this helps anyone!

like image 25
Felix Avatar answered Oct 23 '25 19:10

Felix