简体   繁体   中英

How to prevent non logged in users from viewing a context_processor

Im getting an error of 'AnonymousUser' object is not iterable from this code:

context_proccesors.py

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

How can I exclude this from being seen by non logged in users.

Traceback:

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

Try checking for authentication in your context and either pass or return None:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM