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

后端 未结 9 1881
广开言路
广开言路 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

    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 %}
      

    Paragraph only visible to VIPs

    {% endif %}

提交回复
热议问题