Good Day,
I have a problem with authentication in Django 3.0.
My project depending on giving points for users for every action (like post, comment, like, favorite, ....).
I am using custom context_processors to get these values in multiple templates.
My problem : when i am logged in .. everything works fine (admin panel, new post, new comment, ....).
when i logged out .. all project get mad and all pages doesn't work .. getting the following error:
'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'
],
},
},
]
Traceback Error:
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
I believe that the solution is in django sessions .. i tried several times and searched here for multiple uestions and answers, but i got failed.
Can anybody help ?
Thanks in-advance for your kind support....
It worked after a simple modifications:
user.request.is_authenticated
.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
Please note:
@Omonbude Emmanuel was true .. it must be request.user.is_authenticated()
because of using Django 3.0.
but it worked with request.user.is_authenticated
without ()
.. and i don't know why ......
Great thanks for you all,
Best Regards,