Django 'logout' TypeError: 'AnonymousUser' object is not iterable
Django 'logout' TypeError: 'AnonymousUser' object is not iterable
美好的一天,
我在 Django 3.0 中遇到身份验证问题。
我的项目取决于为用户的每个操作(例如 post、评论、喜欢、收藏、....)提供积分。
我正在使用自定义 context_processors 在多个模板中获取这些值。
我的问题: 当我登录时..一切正常(管理面板,新 post,新评论,....)。
当我注销时..所有项目都变得疯狂并且所有页面都不起作用..出现以下错误:
'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:\Private\PythonProjects\ProCoers02\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Private\PythonProjects\ProCoers02\src\blog-django-ar-master\src\blog\views.py", line 59, in HomePageView
return render(request, 'blog/home.html', {})
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\template\base.py", line 169, in render
with context.bind_template(self):
File "C:\Users\clt\AppData\Local\Programs\Python\Python38-32\lib\contextlib.py", line 113, in __enter__
return next(self.gen)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\template\context.py", line 246, in bind_template
updates.update(processor(self.request))
File "D:\Private\PythonProjects\ProCoers02\src\blog-django-ar-master\src\common\context_processors.py", line 19, in extra_cp
postsperuser = Post.objects.filter(author=request.user)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\db\models\query.py", line 904, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\db\models\sql\query.py", line 1350, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q
child_clause, needed_inner = self.build_filter(
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\db\models\sql\query.py", line 1284, in build_filter
self.check_related_objects(join_info.final_field, value, join_info.opts)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\db\models\sql\query.py", line 1124, in check_related_objects
for v in value:
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\utils\functional.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 会话中..我尝试了几次并在这里搜索了多个问题和答案,但我都失败了。
有人可以帮忙吗?
感谢in-advance的支持....
您正在上下文处理器中过滤用户。
它只会在用户登录时起作用。
您可以使用 if 语句检查他们是否已登录或使用 try 和 except。
经过简单的修改就可以了:
- 将用户定义为
user.request.is_authenticated
。
- 在 if 语句之前添加上下文作为空字典。
- 使用如下所示的 if 语句。
- 在 if 语句中移动上下文。
- 保持 return 上下文不变。
context_processors.py
def extra_cp(request):
categories = Category.objects.all()
user = request.user.is_authenticated
context = {}
if user:
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
请注意:
@Omonbude Emmanuel 是真的..它必须是 request.user.is_authenticated()
因为使用 Django 3.0.
但它与 request.user.is_authenticated
一起工作而没有 ()
.. 我不知道为什么......
非常感谢大家,
此致,
美好的一天,
我在 Django 3.0 中遇到身份验证问题。
我的项目取决于为用户的每个操作(例如 post、评论、喜欢、收藏、....)提供积分。
我正在使用自定义 context_processors 在多个模板中获取这些值。
我的问题: 当我登录时..一切正常(管理面板,新 post,新评论,....)。
当我注销时..所有项目都变得疯狂并且所有页面都不起作用..出现以下错误:
'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:\Private\PythonProjects\ProCoers02\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Private\PythonProjects\ProCoers02\src\blog-django-ar-master\src\blog\views.py", line 59, in HomePageView
return render(request, 'blog/home.html', {})
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\template\base.py", line 169, in render
with context.bind_template(self):
File "C:\Users\clt\AppData\Local\Programs\Python\Python38-32\lib\contextlib.py", line 113, in __enter__
return next(self.gen)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\template\context.py", line 246, in bind_template
updates.update(processor(self.request))
File "D:\Private\PythonProjects\ProCoers02\src\blog-django-ar-master\src\common\context_processors.py", line 19, in extra_cp
postsperuser = Post.objects.filter(author=request.user)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\db\models\query.py", line 904, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\db\models\sql\query.py", line 1350, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q
child_clause, needed_inner = self.build_filter(
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\db\models\sql\query.py", line 1284, in build_filter
self.check_related_objects(join_info.final_field, value, join_info.opts)
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\db\models\sql\query.py", line 1124, in check_related_objects
for v in value:
File "D:\Private\PythonProjects\ProCoers02\lib\site-packages\django\utils\functional.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 会话中..我尝试了几次并在这里搜索了多个问题和答案,但我都失败了。
有人可以帮忙吗?
感谢in-advance的支持....
您正在上下文处理器中过滤用户。 它只会在用户登录时起作用。 您可以使用 if 语句检查他们是否已登录或使用 try 和 except。
经过简单的修改就可以了:
- 将用户定义为
user.request.is_authenticated
。 - 在 if 语句之前添加上下文作为空字典。
- 使用如下所示的 if 语句。
- 在 if 语句中移动上下文。
- 保持 return 上下文不变。
context_processors.py
def extra_cp(request):
categories = Category.objects.all()
user = request.user.is_authenticated
context = {}
if user:
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
请注意:
@Omonbude Emmanuel 是真的..它必须是 request.user.is_authenticated()
因为使用 Django 3.0.
但它与 request.user.is_authenticated
一起工作而没有 ()
.. 我不知道为什么......
非常感谢大家,
此致,