Django 1.9: 'AnonymousUser' object is not iterable

django

1566 просмотра

1 ответ

192 Репутация автора

I was working on a Django 1.9 project, and suddenly this error popped up when I attempted to view my site's home page as a logged-out user.

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/

Django Version: 1.9.7
Python Version: 2.7.10
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.sites',
 'django.contrib.staticfiles',
 'captcha',
 'debug_toolbar',
 'django_extensions',
 'djstripe',
 'crm',
 'launch',
 'rentals',
 'widget_tweaks']
Installed Middleware:
[u'debug_toolbar.middleware.DebugToolbarMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  174.                     response = self.process_exception_by_middleware(e, request)

File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  172.                     response = response.render()

File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/template/response.py" in render
  160.             self.content = self.rendered_content

File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/template/response.py" in rendered_content
  137.         content = template.render(context, self._request)

File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/template/backends/django.py" in render
  95.             return self.template.render(context)

File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/template/base.py" in render
  204.                 with context.bind_template(self):

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py" in __enter__
  17.             return self.gen.next()

File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/debug_toolbar/panels/templates/panel.py" in _request_context_bind_template
  79.             context = processor(self.request)

File "/Users/me/projects/rentalguru/src/rentals/processors.py" in allCategories
  4.     expense_categories = ExpenseCategory.objects.filter(user=request.user)

File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
  122.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/query.py" in filter
  790.         return self._filter_or_exclude(False, *args, **kwargs)

File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/query.py" in _filter_or_exclude
  808.             clone.query.add_q(Q(*args, **kwargs))

File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/sql/query.py" in add_q
  1243.         clause, _ = self._add_q(q_object, self.used_aliases)

File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/sql/query.py" in _add_q
  1269.                     allow_joins=allow_joins, split_subq=split_subq,

File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/sql/query.py" in build_filter
  1174.             self.check_related_objects(field, value, opts)

File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/sql/query.py" in check_related_objects
  1073.                 for v in value:

File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/utils/functional.py" in inner
  205.         return func(self._wrapped, *args)

Exception Type: TypeError at /
Exception Value: 'AnonymousUser' object is not iterable

I'm not sure what would be causing this, and there's only one Google search result (for this site) for this error. I searched the code for the is_authenticated() method and didn't find anything, so I'm unsure where to turn. Working through the stack trace didn't show any useful (for me) information.

Here is my view:

class HomePageView(TemplateView):
    template_name = 'home.html'

No login decorators or wrapped functions that I can tell.

Let me know if I need to post anything else.

EDIT: Asked for the model, here is the offending context processor instead:

def allCategories(request):
    expense_categories = ExpenseCategory.objects.filter(user=request.user)
    tags = {'categories': expense_categories}
    return tags
Автор: Matthew Calabresi Источник Размещён: 19.07.2016 12:01

Ответы (1)


0 плюса

22721 Репутация автора

I just stumbled myself upon this error. Thankfully the answer was provided in the comments:

As you said you tried to view home page with logged out user and this ExpenseCategory.objects.filter(user=request.user) filtering of Anonymous user (because you are logged out now) seems to be the culprit. Either you should allow only a authenticated user to this view or handle the case where your user is Anonymous

As for myself, I had a view, where I was filtering on a model based on the current user, which apparantly fails, when the user is the AnonymousUser.

I fixed this by adding a check:

if request.user.is_active:
    expense_categories = ExpenseCategory.objects.filter(user=request.user)

Note that some people seem to prefer to check request.user.is_authenticated instead.

If you are dealing with a view that shall be accessed by logged in users only, you can also use the @login_required decorator.

For reference:

Автор: moooeeeep Размещён: 10.04.2017 07:59
Вопросы из категории :
32x32