Question

I have a model that looks like this..

from django.contrib.auth.models import User

class SampleModel(models.Model):
    info1 = models.CharField(max_length = 20)
    info2 = models.CharField(max_length = 20)
    objectAdmin = models.ForeignKey(User)

django by default gives access to users to the entire tables if you allow them, but I want the user that is in that row to be the only one to have access to the entry..

so when a particular user logs in, and he goes to the /admin/myapp/samplemodel/1/ ,he should only be able to edit that object if he is the "objectAdmin" of that entry..

Was it helpful?

Solution

Filter the queryset in admin based on the user logged in.

class SampleModelAdmin(admin.ModelAdmin):
    def queryset(self, request):
        qs = super(SampleModelAdmin, self).queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(objectAdmin = request.user)

This will ensure that the user has access to objects for which he is assigned as admin.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top