In Django, how do I check if a user is in a certain group?

前端 未结 12 2041
借酒劲吻你
借酒劲吻你 2020-11-28 18:25

I created a custom group in Django\'s admin site.

In my code, I want to check if a user is in this group. How do I do that?

12条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 18:54

    I have similar situation, I wanted to test if the user is in a certain group. So, I've created new file utils.py where I put all my small utilities that help me through entire application. There, I've have this definition:

    utils.py
    
    def is_company_admin(user):
        return user.groups.filter(name='company_admin').exists()
    

    so basically I am testing if the user is in the group company_admin and for clarity I've called this function is_company_admin.

    When I want to check if the user is in the company_admin I just do this:

    views.py
    
    from .utils import *
    
    if is_company_admin(request.user):
            data = Company.objects.all().filter(id=request.user.company.id)
    

    Now, if you wish to test same in your template, you can add is_user_admin in your context, something like this:

    views.py
    
    return render(request, 'admin/users.html', {'data': data, 'is_company_admin': is_company_admin(request.user)})
    

    Now you can evaluate you response in a template:

    users.html
    
    {% if is_company_admin %}
         ... do something ...
    {% endif %}
    
    

    Simple and clean solution, based on answers that can be found earlier in this thread, but done differently. Hope it will help someone.

    Tested in Django 3.0.4.

提交回复
热议问题