permwrapper and permlookupdict proxy the permissions system into objects that the template system can understand to fix item in perms someapp and getitem interaction we need to define iter see 18979 for details i am large i contain multitudes lookup by someapp or someapp someperm in perms the name refers to module return context variables required by apps that use django s authentication system if there is no user attribute in the request use anonymoususer from django contrib auth permwrapper and permlookupdict proxy the permissions system into objects that the template system can understand to fix item in perms someapp and __getitem__ interaction we need to define __iter__ see 18979 for details i am large i contain multitudes lookup by someapp or someapp someperm in perms the name refers to module return context variables required by apps that use django s authentication system if there is no user attribute in the request use anonymoususer from django contrib auth
class PermLookupDict:
    def __init__(self, user, app_label):
        self.user, self.app_label = user, app_label

    def __repr__(self):
        return str(self.user.get_all_permissions())

    def __getitem__(self, perm_name):
        return self.user.has_perm("%s.%s" % (self.app_label, perm_name))

    def __iter__(self):
        
        
        raise TypeError("PermLookupDict is not iterable.")

    def __bool__(self):
        return self.user.has_module_perms(self.app_label)


class PermWrapper:
    def __init__(self, user):
        self.user = user

    def __repr__(self):
        return f"{self.__class__.__qualname__}({self.user!r})"

    def __getitem__(self, app_label):
        return PermLookupDict(self.user, app_label)

    def __iter__(self):
        
        raise TypeError("PermWrapper is not iterable.")

    def __contains__(self, perm_name):
        
        if "." not in perm_name:
            
            return bool(self[perm_name])
        app_label, perm_name = perm_name.split(".", 1)
        return self[app_label][perm_name]


def auth(request):
    
    if hasattr(request, "user"):
        user = request.user
    else:
        from django.contrib.auth.models import AnonymousUser

        user = AnonymousUser()

    return {
        "user": user,
        "perms": PermWrapper(user),
    }