【问题标题】:Django: Context processor error for anonymous userDjango:匿名用户的上下文处理器错误
【发布时间】:2016-12-09 06:58:38
【问题描述】:

您好,我有一个存储用户操作的模型。此模型用于向登录用户显示通知。 现在的问题是代码在登录用户下工作正常,但是如果我在注销后打开应用程序的主页,则会出现以下错误。

TypeError at /

'AnonymousUser' object is not iterable

Request Method:     GET
Request URL:    http://127.0.0.1:8000/
Django Version:     1.10
Exception Type:     TypeError
Exception Value:    

**'AnonymousUser' object is not iterable**

Exception Location:     /Library/Python/2.7/site-packages/django/utils/functional.py in inner, line 235
Python Executable:  /usr/bin/python
Python Version:     2.7.10

我认为问题在于我在应用程序中使用的模板上下文处理器。

请帮忙。 上下文代码

from models import notifications


def activ_notification(request):
    active = notifications.objects.filter(to_user=request.user,viewed=False)[:10]

    return({'alert':active})

设置

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'task.notification.activ_notification',
            ],
        },
    },
]

【问题讨论】:

    标签: django django-templates django-context


    【解决方案1】:

    尝试在您的视图中添加is_authenticated check:

    def activ_notification(request):
        active = []
        if request.user.is_authenticated():    
            active = notifications.objects.filter(to_user=request.user,viewed=False)[:10]
    
        return({'alert':active})
    

    【讨论】:

      猜你喜欢
      • 2019-06-26
      • 2016-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-20
      • 2015-08-19
      相关资源
      最近更新 更多