Home > OS >  Unable to add post in Django getting TypeError: 'AnonymousUser' object is not iterable
Unable to add post in Django getting TypeError: 'AnonymousUser' object is not iterable

Time:12-28

When I am clicking on the modal button to add a new post in Django. I am getting the below traceback

Traceback (most recent call last):
  File "D:\Django_AJAX_Latest\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "D:\Django_AJAX_Latest\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\Django_AJAX_Latest\src\posts\views.py", line 22, in post_list_and_create
    author = Profile.objects.get(user = request.user)
  File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\query.py", line 428, in get   
    clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
  File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\query.py", line 974, in filter    return self._filter_or_exclude(False, args, kwargs)
  File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\query.py", line 992, in _filter_or_exclude
    clone._filter_or_exclude_inplace(negate, args, kwargs)
  File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\query.py", line 999, in _filter_or_exclude_inplace
    self._query.add_q(Q(*args, **kwargs))
  File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\sql\query.py", line 1375, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\sql\query.py", line 1396, in _add_qn _add_q
    child_clause, needed_inner = self.build_filter(                                             n build_filter
  File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\sql\query.py", line 1302, in build_filter                                                                                  n check_related_objects
    self.check_related_objects(join_info.final_field, value, join_info.opts)
  File "D:\Django_AJAX_Latest\env\lib\site-packages\django\db\models\sql\query.py", line 1136, iner    return func(self._wrapped, *args)n check_related_objects
    for v in value:
nctional.py", line 249, in inner    return func(self._wrapped, *args)s)
TypeError: 'AnonymousUser' object is not iterable

Below are my files:

posts/views.py

from django.shortcuts import render
from .models import Post
from django.http import JsonResponse
from .forms import PostForm
from profiles.models import Profile


def is_ajax(request):
    return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'

def post_list_and_create(request):
    form = PostForm(request.POST or None)
    if is_ajax(request=request):
        if form.is_valid():      
            author = Profile.objects.get(user = request.user)
            instance = form.save(commit=False)
            instance.author = author
            instance.save()

    context = {
        'form': form,
    }

    return render(request, 'posts/main.html', context)

profiles/models.py

from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(default=True)
    avatar = models.ImageField(default='avatar.jpg', upload_to='avatars')
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"Profile of the user {self.user.username}"

posts/models.py

from django.db import models
from django.contrib.auth.models import User
from profiles.models import Profile

# Create your models here.

class Post(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    liked = models.ManyToManyField(User, blank=True)
    author = models.ForeignKey(Profile, on_delete=models.CASCADE)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.title)

    @property
    def like_count(self):
        return self.liked.all().count()

    class Meta:
        ordering = ("-created",)

requirements.txt

asgiref==3.4.1
backports.zoneinfo==0.2.1
Django==4.0
django-crispy-forms==1.13.0
Pillow==8.4.0
sqlparse==0.4.2
tzdata==2021.5

I have already tried using the request.is_authenticated attribute but it is giving me another error as AttributeError: 'WSGIRequest' object has no attribute 'is_authenticated'.

Can someone please help me with this?

CodePudding user response:

Error request.user is an anonymous user means that there is no logged in User,

Try using login_required decorator, to make sure that only logged-in users can access the view.

from django.contrib.auth.decorators import login_required

@login_required
def post_list_and_create(request):
...

CodePudding user response:

Anonymous user means that the user is not logged in. You need to logged in your user before it access any view.

Step 1. import the the built-in method

from django.contrib.auth import login as auth_login

Step 2.

Logged in your user in login view

auth_login(request, user)

Note Use this decorator above views except Auth that the user is not access any view without loggin. @login_required

  • Related