I am creating a website in pure django where I have the following model.
class GoodsDetails(models.Model):
serial_number = models.CharField(max_length=100)
goods_description = models.CharField(max_length=100)
quantity = models.CharField(max_length=100)
gross_weight = models.CharField(max_length=100)
is_active = models.BooleanField()
def __str__(self):
return f"{self.serial_number}"
I have registered the model in the administration and I want to show all the model instances to the superuser but to non-superusers, I want to show only those instances where is_active = False
. How can this be achieved in django administration?
I researched about it and think that I should create a custom permission for this job. However, I think that modifying the admin views logic would be better because in this case, changing the ORM query a bit will get the job done. Any other approaches are also welcome.
Thank you for your suggestions and/or solutions :)
In the admin.py
add
from django.contrib import admin
from .models import GoodsDetails
@admin.register(GoodsDetails)
class GoodsDetailsAdmin(admin.ModelAdmin):
list_display = ('id', 'serial_number', 'goods_description', 'quantity', 'gross_weight', 'is_active')
def get_queryset(self, request):
qs = super().get_queryset(request)
if request.user.is_superuser:
return qs
else:
return qs.filter(is_active=False)