Added content_type filtering in Permission querying example.

This commit is contained in:
Nauman Tariq 2017-04-26 12:28:06 -05:00 committed by Tim Graham
parent 92bc727271
commit 6684af1e43
1 changed files with 11 additions and 4 deletions

View File

@ -275,25 +275,32 @@ afterward, in a test or view for example, the easiest solution is to re-fetch
the user from the database. For example::
from django.contrib.auth.models import Permission, User
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import get_object_or_404
from myapp.models import BlogPost
def user_gains_perms(request, user_id):
user = get_object_or_404(User, pk=user_id)
# any permission check will cache the current set of permissions
user.has_perm('myapp.change_bar')
user.has_perm('myapp.change_blogpost')
permission = Permission.objects.get(codename='change_bar')
content_type = ContentType.objects.get_for_model(BlogPost)
permission = Permission.objects.get(
codename='change_blogpost',
content_type=content_type,
)
user.user_permissions.add(permission)
# Checking the cached permission set
user.has_perm('myapp.change_bar') # False
user.has_perm('myapp.change_blogpost') # False
# Request new instance of User
# Be aware that user.refresh_from_db() won't clear the cache.
user = get_object_or_404(User, pk=user_id)
# Permission cache is repopulated from the database
user.has_perm('myapp.change_bar') # True
user.has_perm('myapp.change_blogpost') # True
...