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.
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.
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!
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