Django'logout'TypeError:'AnonymousUser'对象不可迭代

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django'logout'TypeError:'AnonymousUser'对象不可迭代相关的知识,希望对你有一定的参考价值。

早安,

我在Django 3.0中对身份验证有问题。

我的项目取决于为每个操作(例如帖子,评论,喜欢,喜欢...)给用户加分。

我正在使用自定义context_processors在多个模板中获取这些值。

我的问题:当我登录..一切正常(管理面板,新帖子,新评论等)。

当我注销时..所有项目都发疯了,并且所有页面都无法工作..收到以下错误:

'AnonymousUser' object is not iterable

Models.py

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    likes = models.ManyToManyField(User, related_name='likes', blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    favourite = models.ManyToManyField(User, related_name='favourite', blank=True)

    def __str__(self):
        return self.title

class Comment(models.Model):
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='commenter')
    content = models.TextField(verbose_name='Comment')
    post = models.ForeignKey(
        Post, on_delete=models.CASCADE, related_name='comments')

    def __str__(self):
        return '{} Commented On {}.'.format(self.user, self.post)

Views.py

def logout_user(request):
    logout(request)
    return render(request, 'user/logout.html', {})

context_processors.py

def extra_cp(request):
    categories = Category.objects.all()

    postsperuser = Post.objects.filter(author=request.user)
    postsperusercount = Post.objects.all().annotate(posts_count=Count('title')).filter(author=request.user)
    postspoints = postsperusercount.aggregate(posts_score=Count('posts_count') * 1000)

    commentsperuser = Comment.objects.filter(user=request.user)
    commentsperusercount = Comment.objects.all().annotate(comments_count=Count('content')).filter(user=request.user)
    commentspoints = commentsperusercount.aggregate(comments_score=Count('comments_count') * 350)

    total_points = postspoints['posts_score'] + commentspoints['comments_score']

    comment_list = Comment.objects.filter(user=request.user)

    context = {
        'categories': categories,
        'postsperuser': postsperuser,
        'postspoints':postspoints,
        'commentsperuser':commentsperuser,
        'commentspoints':commentspoints,
        'comment_list': comment_list,
        'total_points': total_points,
                    }
    return context

settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR + '/templates/', ],
        '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',
                'common.context_processors.extra_cp'

            ],
        },
    },
]

追踪错误:

Django version 3.0.3, using settings 'my_blog.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Internal Server Error: /
Traceback (most recent call last):
  File "D:PrivatePythonProjectsProCoers02libsite-packagesdjangocorehandlersexception.py", line 34, in inner
    response = get_response(request)
  File "D:PrivatePythonProjectsProCoers02libsite-packagesdjangocorehandlersase.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "D:PrivatePythonProjectsProCoers02libsite-packagesdjangocorehandlersase.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:PrivatePythonProjectsProCoers02srclog-django-ar-mastersrclogviews.py", line 59, in HomePageView
    return render(request, 'blog/home.html', {})
  File "D:PrivatePythonProjectsProCoers02libsite-packagesdjangoshortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "D:PrivatePythonProjectsProCoers02libsite-packagesdjango	emplateloader.py", line 62, in render_to_string
    return template.render(context, request)
  File "D:PrivatePythonProjectsProCoers02libsite-packagesdjango	emplateackendsdjango.py", line 61, in render
    return self.template.render(context)
  File "D:PrivatePythonProjectsProCoers02libsite-packagesdjango	emplatease.py", line 169, in render
    with context.bind_template(self):
  File "C:UserscltAppDataLocalProgramsPythonPython38-32libcontextlib.py", line 113, in __enter__
    return next(self.gen)
  File "D:PrivatePythonProjectsProCoers02libsite-packagesdjango	emplatecontext.py", line 246, in bind_template
    updates.update(processor(self.request))
  File "D:PrivatePythonProjectsProCoers02srclog-django-ar-mastersrccommoncontext_processors.py", line 19, in extra_cp
    postsperuser = Post.objects.filter(author=request.user)
  File "D:PrivatePythonProjectsProCoers02libsite-packagesdjangodbmodelsmanager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "D:PrivatePythonProjectsProCoers02libsite-packagesdjangodbmodelsquery.py", line 904, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "D:PrivatePythonProjectsProCoers02libsite-packagesdjangodbmodelsquery.py", line 923, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "D:PrivatePythonProjectsProCoers02libsite-packagesdjangodbmodelssqlquery.py", line 1350, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "D:PrivatePythonProjectsProCoers02libsite-packagesdjangodbmodelssqlquery.py", line 1377, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "D:PrivatePythonProjectsProCoers02libsite-packagesdjangodbmodelssqlquery.py", line 1284, in build_filter
    self.check_related_objects(join_info.final_field, value, join_info.opts)
  File "D:PrivatePythonProjectsProCoers02libsite-packagesdjangodbmodelssqlquery.py", line 1124, in check_related_objects
    for v in value:
  File "D:PrivatePythonProjectsProCoers02libsite-packagesdjangoutilsfunctional.py", line 225, in inner
    return func(self._wrapped, *args)
TypeError: 'AnonymousUser' object is not iterable
[02/Apr/2020 00:23:21] "GET / HTTP/1.1" 500 137245

[我相信解决方案是在django会话中。我尝试了几次,并在这里搜索了多个参考和答案,但是我失败了。

有人可以帮忙吗?

感谢您的支持。...>

[Good Day,我对Django 3.0中的身份验证有疑问。我的项目取决于为用户的每项操作(例如发布,评论,喜欢,喜欢...)提供积分。我正在使用自定义...

答案

您正在上下文处理器中过滤用户。只有在用户登录后才能使用。您可以使用if语句来检查它们是否已登录,或者使用try和except。

另一答案

经过简单的修改后就起作用了:

以上是关于Django'logout'TypeError:'AnonymousUser'对象不可迭代的主要内容,如果未能解决你的问题,请参考以下文章

前后端分离 Spring Security 对登出.logout()的处理

pom文件出现Element 'xxxxxxx' cannot have character [children],because the type's content typ

login() got an unexpected keyword argument 'extra_context'

jQuery()中,on()方法

覆盖 Django admin 中的注销链接

Web在线聊天室 --- 退出登录