Reputation: 53
I have two tables
Employee
-----
username
organisation_id
email
Organisation
------------
organisation_id
company_name
User_A->organisation_1
User_B->organisation_1
User_C->organisation_2
User_D->organisation_2
when user_A login he should only see User_A and User_B This code should be like below, logic is first we need to find the current user organization and conditionally display the results in admin page Django admin code
admin.site.register(Employee, CustomUserAdmin)
admin.site.register(Organization)
class CustomUserAdmin(UserAdmin):
def filter_view(request):
current_user = request.user
organization_id =employees.objects.get(id=current_user.id).organization_id
List_display = ('username', 'email','Organizations.objects.filter(id=organization_id)')
Upvotes: 0
Views: 718
Reputation: 53
I am answering this question for helping others, I modified my code like this for multiple user types, this code will help you for that situation so that only users related to the department can see other user but superuser can control everyone. thankyou for @ruddra and @MK Patel for your valuable effort.
> class RestrictedFormAdmin(admin.ModelAdmin):
> class Meta:
> model = Employee
> def get_queryset(self, request):
> if request.user.is_superuser:
> return super().get_queryset(request)
> return super().get_queryset(request).filter(organization_id=request.user.employee.organization_id)
>
> admin.site.register(Employee,RestrictedFormAdmin)
Upvotes: 0
Reputation: 51988
You can override get_queryset(request)
method:
I am assuming you have a onetoone relation between employee and user
class Employee(models.Model):
user = models.OneToOneField(User)
Then override the ModelAdmin
class like this:
class CustomUserAdmin(UserAdmin):
def get_queryset(self, request):
return super().get_queryset(request).filter(organisation_id=request.user.employee.organisation_id)
Upvotes: 1
Reputation: 1394
You can write list_display
is...
list_display = ('username', 'email', 'filtered_organisation')
And write a method for filtered_organisation as below...
def filtered_organisation(self, obj):
return Organizations.objects.filter(id=organization_id)
For more reference click here
Upvotes: 1