Checking user group membership in permission_required
<p>How would I check if a user is a part of a group inside the <code>permission_required</code> decorator?</p>

<p>This is what I have currently but it doesn't seem to check it..</p>

<pre><code>@permission_required(['user.is_super_user', "'NormalUser' in user.groups.all"], raise_exception=True)
</code></pre>

<p>This is supposed to check whether the user is a super user OR the user is part of the group <code>NormalUser</code> but when I try to access the site it just give me a 403 error when the user is part of the <code>NormalUser</code> group.</p>

<p>Is there a way I can get this done? I only want to use <code>permission_required</code> decorator, nothing else :S</p>

<p>You should use <a href="https://docs.djangoproject.com/en/1.10/topics/auth/default/#django.contrib.auth.decorators.user_passes_test" rel="nofollow"><code>user_passes_test</code></a> for this. The <code>permission_required</code> decorator checks permissions. It doesn't make sense to use it here.</p>

<p>First, you need to define a test function that returns True if the user is a superuser or is in the <code>NormalUser</code> group:</p>

<pre><code>def superuser_or_normaluser(user):
    return user.is_superuser or user.groups.filter(name='NormalUser').exists()
</code></pre>

<p>Then you can use that test function with the <code>user_passes_test</code> decorator.</p>

<pre><code>@user_passes_test(superuser_or_normaluser, raise_exception=True)
</code></pre>

python django python-2.7 django-admin django-views