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