I want to have an admin where any operator who logs in the admin dashboard can only view their package objects and not see/change package objects added by other operators (from user).
My models:
class Package(models.Model):
operator = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
destination = models.ForeignKey(Destination, on_delete=models.CASCADE)
package_name = models.CharField(max_length=255)
city = models.CharField(max_length=255)
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,
related_name='profile', on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
user_type = models.CharField(max_length=1, choices=USER_TYPES, default='g')
first_name = models.CharField(max_length=255, default="")
My package/admin.py:
class PackageAdmin(ModelAdmin):
icon_name = 'explore'
autocomplete_fields = ['destination']
list_display = ('image_display','package_name', 'featured', 'price', 'discounted_price',
'savings', 'fix_departure', 'rating',
'date_created',)
image_display = AdminThumbnail(image_field='thumbnail')
image_display.short_description = 'Image'
readonly_fields = ['image_display']
def get_queryset(self, request):
abc = super(PackageAdmin, self).get_queryset(request)
if request.user.is_superuser:
return abc
else:
operator = request.user.id
return abc.filter(operator=operator)
I have overridden the get_queryset(self, request) function but it is not working.
My update:
I see another problem here. Now, although operator cant see/modify another objects but can add the package object on another operators name using email from the dropdown.
The two solutions will be:
Package.operator
is a ForeignKey
to the UserProfile
model, you need to pass an instance of this model to the filter with request.user.profile
using the related_name
from the OneToOneField
def get_queryset(self, request):
queryset = super(PackageAdmin, self).get_queryset(request)
if request.user.is_superuser:
return abc
else:
operator = request.user.profile
return queryset.filter(operator=operator)