Django 如何防止未登录用户查看上下文处理器

Django 如何防止未登录用户查看上下文处理器,django,Django,Im收到“AnonymousUser”对象错误,无法从此代码中删除: context_proccessors.py def subscriptions(request): context = { 'mysubs': Subscription.objects.filter(user=request.user, is_active=True) } return context 我如何才能排除未登录用户看到此内容 回溯: Tr

Im收到“AnonymousUser”对象错误,无法从此代码中删除:

context_proccessors.py

 def subscriptions(request):
        context = {
            'mysubs': Subscription.objects.filter(user=request.user, is_active=True)
        }
        return context
我如何才能排除未登录用户看到此内容

回溯:

Traceback (most recent call last):
  File "/Users/Tyler/PycharmProjects/whatstheupdatev2/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/Tyler/PycharmProjects/whatstheupdatev2/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 156, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/Tyler/PycharmProjects/whatstheupdatev2/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 154, in _get_response
    response = response.render()
  File "/Users/Tyler/PycharmProjects/whatstheupdatev2/venv/lib/python3.7/site-packages/django/template/response.py", line 106, in render
    self.content = self.rendered_content
  File "/Users/Tyler/PycharmProjects/whatstheupdatev2/venv/lib/python3.7/site-packages/django/template/response.py", line 83, in rendered_content
    content = template.render(context, self._request)
  File "/Users/Tyler/PycharmProjects/whatstheupdatev2/venv/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/Users/Tyler/PycharmProjects/whatstheupdatev2/venv/lib/python3.7/site-packages/django/template/base.py", line 169, in render
    with context.bind_template(self):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/contextlib.py", line 112, in __enter__
    return next(self.gen)
  File "/Users/Tyler/PycharmProjects/whatstheupdatev2/venv/lib/python3.7/site-packages/django/template/context.py", line 246, in bind_template
    updates.update(processor(self.request))
TypeError: 'NoneType' object is not iterable

尝试在您的上下文中检查身份验证,并通过或不返回:

 def subscriptions(request):
    if request.user.is_authenticated:
        context = {
            'subs': Subscription.objects.filter(user=request.user, is_active=True)
        }
        return context
    else:
       return {}

尝试在您的上下文中检查身份验证,并通过或不返回:

 def subscriptions(request):
    if request.user.is_authenticated:
        context = {
            'subs': Subscription.objects.filter(user=request.user, is_active=True)
        }
        return context
    else:
       return {}

当我使用它时,我得到这个返回
'NoneType'对象是不可编辑的
你从哪里得到这个错误的。因为听起来你可能有更多的代码试图不读。您是否能够发布回溯?当我使用该回溯时,我获取此回溯
“非类型”对象不可编辑
您从何处获取此错误。因为听起来你可能有更多的代码试图不读。你能发布回溯吗?下面的链接应该比我的答案更能帮助你。但听起来我们需要传一本空字典,而不是一本都没有。下面的链接应该比我的答案更能帮助你。但听起来我们需要传一本空字典,而不是一本都没有。