Created
August 21, 2014 04:33
-
-
Save arthuralvim/78129975b31d457fffc6 to your computer and use it in GitHub Desktop.
A template tag to check if an user belongs to a specific group.
I suggest using Django's ORM filter(...).first() if you want to avoid try/catch as it returns None if nothing found.
Using the walrus operator I wrote it this way:
@register.filter(name="has_group")
def has_group(user, group_name) -> bool:
"""Check if User Belongs to Given Group.
This should be avoided as it is better to have specific permissions attached
to models.
Use:
...
{% if request.user|has_group:"mygroup" %}
<p>User belongs to my group
{% else %}
<p>User doesn't belong to mygroup</p>
{% endif %}
"""
if group := Group.objects.filter(name=group_name).first():
return group in user.groups.all()
return FalsePlus there is no reason to return True if ..., in operator https://docs.python.org/3/reference/expressions.html#in returns boolean, there is no need to check if boolean, you can return just that.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've added try except, because if the group doesn't exist I've got error