Search code examples
pythondjangodjango-permissions

Is there a way to make a user only view related objects to him in a model in django administration?


I'm new to django and i'm trying to make a school web app fully inside the django administration.

The thing i'm trying to do is to make a permission for the students that gives them the ability to only see the scores which its student field is same to the student user.

This is my Student model:

class Student(models.Model):
    student_name = models.CharField(max_length=12)
    student_last_name = models.CharField(max_length=12,null=True)
    student_age = models.PositiveSmallIntegerField(null=True)
    student_class = models.ForeignKey(Clas,on_delete=models.SET_NULL,null=True)
    student_idnum = models.CharField(max_length=15,null=True)
    user = models.OneToOneField(User,on_delete=models.SET_NULL,null=True)
    pub_date = models.DateTimeField("date published")
    def __str__(self):
        return self.student_name

And this is my students Score model:

class Score(models.Model):
    exam = models.ForeignKey(Exam,on_delete=models.SET_NULL,null=True)
    student = models.ForeignKey(Student, on_delete=models.CASCADE,null=True)
    score = models.FloatField(null=True)
    def __str__(self):
        return str(self.score)

I have seen the Meta model which i should use it for the custom permission, but i really don't know what should i do.


Solution

  • The official docs has an example that does what you want.

    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

    from django.contrib import admin
    
    class MyModelAdmin(admin.ModelAdmin):
        def get_queryset(self, request):
            qs = super().get_queryset(request)
            if request.user.is_superuser:
                return qs
            return qs.filter(author=request.user)
    
    admin.site.register(MyModel, MyModelAdmin)
    

    You can change the queryset to fit your needs.