Last Updated: February 25, 2016
·
734
· oscarcp

Check against multiple m2m fields in django

def hasmodelpermission(user, object, allow=[]):

"""
Check if the user is in one of the m2m fields of the object.
The function checks the *allow* list and checks one
 by one until it finds one that returns True.

 Arguments

 :user: User object
 :objectl: Object to check
 :allow: List of fields to check if the user is in them, can be for example:
            admins or groupies
 """
for role in allow:
    group = getattr(space, role)
    if user in group.all():
        return True
    else:
        return False

Example:

Picture