Silvering Silvering - 2 months ago 37
Python Question

Display objects related current user django admin

I'm trying to display only objects related to the current user. Users can upload a file and then they can only see their files in the admin. Here is my models :

class Share(models.Model):
owner = models.ForeignKey(User, default='')
title = models.CharField("File's title", max_length=100, unique=True, default='File')
zip_file = models.FileField('Shared File', upload_to=content_zip_name, validators= [validation_zip])


and my admin.py

from django.contrib import admin
from share.models import Share

class ShareAdmin(admin.ModelAdmin):
list_display = ('title',)
save_as = True

def queryset(self, request):
qs = super(ShareAdmin, self).queryset(request)
if request.user.is_superuser:
return qs
return qs.filter(owner=request.user)

admin.site.register(Share, ShareAdmin)


I tried with overriding the queryset function but doesn't work..any idea?

Answer

You've confused the queryset method (used with list_filter) with the get_queryset method:

The get_queryset method on a ModelAdmin returns a QuerySet of all model instances that can be edited by the admin site. One use case for overriding this method is to show objects owned by the logged-in user.

[Emphasis mine]

class ShareAdmin(admin.ModelAdmin):
    list_display = ('title',)
    save_as = True

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