0

I am creating a Django application for multiple universities. Here are the Model classes I have used.

class Institute(models.Model):
    name=models.CharField(max_length=200)
    def __str__(self):
        return self.name

class Applicant(models.Model):
    name = models.CharField(max_length=200)
    institute=models.ForeignKey(Institute,on_delete=models.CASCADE)
    def __str__(self):
         return self.name

I have created a staff user for each institute but the change list of applicants is also showing the applicants who are not of the same institute. I want to modify admin page change list so that it will list only the applicants which belong to that particular institute. Currently my Applicant page change list look like this for every institute from which I have to remove some applicants.

Current change list

Current change list

2 Answers2

0

It sounds like you need to support multi-tenancy. In other words, some "admin" type users will "belong" to an institute, and as such, when they log in, they should only see applicants from their institute.

Unfortunately, this can be kind of a tough problem to solve. If you are using postgres as your database, Django Tenant Schemas is pretty cool. However, at least in my experience with it, I was unable to have a user that could see ALL objects (not sure if you need that or not).

If that does not suit your needs, there are of course other packages that attempt to solve the problem in different ways, a google search should bring these up.

If none of these packages suit your needs you could potentially roll your own multi-tenancy using the Django Sites framework and custom users.

MrName
  • 2,363
  • 17
  • 31
0

Thanks to @shahbaz ahmand I am just writing the answer given in the comment.

With Django 3.2 override get_queryset() in admin.py:

from django.contrib import admin

class ApplicantAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(institute=request.user.institute)
admin.register(Applicant, ApplicantAdmin)

Notice I am assuming a One to one relationship between Institute and User.

  • If you want only filtered queryset then you can override **get_queryset()** https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_queryset – Md Shahbaz Ahmad Sep 08 '21 at 20:44
  • Amazing @shahbazahmad, 4 years and you just gave the right answer on a comment! Thanks a lot, I will edit this awful hack and fix my app as well xD. – Vero E. Arriola Sep 10 '21 at 06:37