0
votes

DJANGO

In ADMIN PANEL using my superuser account I want to give permissions at users to view/change/delete to some objects , not all of them from a Model.By default in ADMIN PANEL you can give permissions for entire Model and not for some objects from it(Model).

I will give you an example:

class Professor(models.Model):
user                = models.ForeignKey(User,on_delete=models.CASCADE) 
lastname            = models.CharField(max_length=25,null=True,blank=False)
firstname           = models.CharField(max_length=25,null=True,blank=False)
email               = models.EmailField(max_length=40,null=True,blank=False)


class Course(models.Model):
name            = models.CharField(max_length=50,null=True,blank=False)
professor       = models.ForeignKey(Professor,on_delete=models.CASCADE)
content         = models.TextField(blank=True,null=True,help_text='')

For example I will create 3 courses: X,Y,Z. The professor teaches Y and Z. The flow is:with my superuser I will create an user for this professor from Admin Panel and I will give him STAFF STATUS and I want to give him also permissions only for 2 objects from Model Course (Y and Z) not for all.All of these I want to be changed from Admin Panel to be easier.

How can I do that?

In the final I want to be easy to give permission from ADMIN PANEL not to entire Model but to some objects from it.

Thank you so much.

1

1 Answers

0
votes

As you are using the django admin you can use the has_change_permission method of ModelAdmin:

class CourseAdmin(admin.ModelAdmin):
    def has_change_permission(self, request, obj=None):
        if obj is None:
            return True
        return request.user == obj.professor

Note: the first check on None is needed as the documentation says:

if obj is None, should return True or False to indicate whether viewing of objects of this type is permitted in general.

This works, but the list view still displays all the Course objects. Making it hard for professors to know which ones they are allowed to edit. We can change the objects displayed in the list view using the get_queryset method:

class CourseAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        return queryset.filter(professor=request.user)

Note: you might want to edit both methods for superusers.