Search code examples
pythondjangoadminuser-permissions

How can we redirect users to specified admin in Django?


I'm working on leave management system where a couple of users report to a particular manager (admin in terms of django, assume if there were more that one admin).

from django.db import models
from django.contrib.auth.models import User

CHOICES = (('1','Earned Leave'),('2','Casual Leave'),('3','Sick Leave'),('4','Paid Leave'))

class Leave(models.Model):

    name = models.CharField(max_length = 50)
    user = models.ForeignKey(User, on_delete = models.CASCADE, null =True)
    employee_ID = models.CharField(max_length = 20)
    department = models.CharField(max_length = 15)
    designation = models.CharField(max_length = 15)
    type_of_leave = models.CharField(max_length = 15, choices = CHOICES, default = None)
    from_date = models.DateField(help_text = 'mm/dd/yy')
    to_date = models.DateField(help_text = 'mm/dd/yy')
    reporting_manager = models.CharField(max_length = 50, default = None)
    reason = models.CharField(max_length= 180)
    accepted = models.BooleanField(('approval status'), default=False)


    def __str__(self):
         return self.name

my application panel

I've tried tweaking my admin.py by using loops and comparing the reporting_manager column, but I couldn't reach my goal. I tried even using built-in user permissions, but that didn't help me. In brief, if there are more than admin with their names. The data/form should be visible to only those admin(s), whose name was mentioned in the form which was submitted y the user.


Solution

  • I didn't quite understand the model and its fields. anyway you should override the get_queryset function in the AdminModel, and filter the queryset, like this

    class LeaveAdmin(admin.ModelAdmin):
        def get_queryset(self, request):
            qs = super().get_queryset(request)
    
            #### return everything if the admin is superuser
            if request.user.is_superuser:
                return qs
    
            ###else do the filtering here based on the staff name [username or anything else]
            return qs.filter(reporting_manager=request.user.username)