如何防止未登录的用户查看context_processor

时间:2019-04-01 21:40:06

标签: django

无法从此代码迭代出“ AnonymousUser”对象的错误:

context_proccesors.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

1 个答案:

答案 0 :(得分:1)

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

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