How to check (in template) if user belongs to a group

后端 未结 9 1859
广开言路
广开言路 2020-12-07 20:38

How to check in template whether user belongs to some group?

It is possible in a view which is generating the template but what if I want

相关标签:
9条回答
  • 2020-12-07 20:50

    Although the answer given by mishbah is right but it didn't work for me.

    I am using Django 2.2.7 and i figured out that register = template.Library() should be replaced with from django.template.defaultfilters import register.

    i hope someone will find it useful.

    0 讨论(0)
  • 2020-12-07 20:50

    The easiest way that I found is by adding all groups name to the context by using a context_preprocessor

    In your app create a file context_processors.py and add the following content:

    def user_groups_processor(request):
        groups = []
        user = request.user
        if user.is_authenticated:
            groups = list(user.groups.values_list('name',flat = True))
        return {'groups': groups}
    
    

    in your settings, add the new context processor

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                # ... some options here ...
                 "context_processors": [
                    "my_app.context_processors.user_groups_processor"
                ],
            },
        },
    ]
    

    Or if you prefer in settings.py

    TEMPLATES[0]['OPTIONS']['context_processors'].append("my_app.context_processors.user_groups_processor")
    

    After that in your templates you can use:

    {% if 'vip' in groups %}
      <p>Paragraph only visible to VIPs</p>
    {% endif %}
    
    0 讨论(0)
  • 2020-12-07 20:58

    In your template

    {% ifequal user.groups.all.0.name "user" %}
      This is User
    {% endifequal %}
      

    0 讨论(0)
  • 2020-12-07 21:03

    I'd say that the best way is:

    yourapp/templatetags/templatetagname.py

    from django import template
    
    register = template.Library()
    
    @register.filter(name='has_group')
    def has_group(user, group_name):
        return user.groups.filter(name=group_name).exists()
    

    yourapp/templates/yourapp/yourtemplate.html:

    {% load has_group %}
    
    {% if request.user|has_group:"mygroup" %} 
        <p>User belongs to my group</p>
    {% else %}
        <p>User does not belong to my group</p>
    {% endif %}
    

    EDIT: added line with template tag loading as was advised in comments.

    EDIT2: fixed minor typo.

    0 讨论(0)
  • 2020-12-07 21:04

    You can use this:

    {% for group_for in request.user.groups.all %}
        {% if group_for.name == 'Customers' %}
            Text showed to users in group 'Customers'
        {% elif group_for.name == 'Sellers' %}
            Text showed to users in group 'Sellers'
        {% endif %}
    {% endfor %}
    

    This is iterating through groups related to the user who makes the request and printing the text if the name of the iterated group equals 'Customers', 'Sellers', etc

    0 讨论(0)
  • 2020-12-07 21:04
    {% if target_group in user.groups.all.0.name %}
        # do your stuff
    {% endif %}
    
    0 讨论(0)
提交回复
热议问题