Home > front end >  Why do I get an API GET error as an anonymousUser even when using IsAuthenticatedOrReadOnly?
Why do I get an API GET error as an anonymousUser even when using IsAuthenticatedOrReadOnly?

Time:01-11

Im learning Django followed a book and tutorials. Anyways I started my own project, where users can create Posts for other to see. My problem comes when someone is not logged in and makes a GET request ie:PostListCreate below, the api crashes even tho I have permissions as IsAuthenticatedOrReadOnly. I get the error TypeError: Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x104d2f760>.

Also I have models.ForeignKey(User, on_delete=models.CASCADE) in the model.py for Post model. Saw this might have something to do with it but unsure.

Have spent three hours researching it and can't find a solution. What do I need to change or edit to be able to have a successful GET request without authentication.

  • api/views.py
from rest_framework import generics, permissions
from .serializers import PostSerializer
from post.models import Post

class PostListCreate(generics.ListCreateAPIView):
    serializer_class = PostSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    def get_queryset(self):
        user = self.request.user
        return Post.objects.filter(user=user).order_by('-created')

    def perform_create(self,serializer):
        serializer.save(user=self.request.user)

class PostRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = PostSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    def get_queryset(self):
        user = self.request.user
        return Post.objects.filter(user=user)
  • model.py
from django.db import models
from django.contrib.auth.models import User

class Post(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True)
   
    created = models.DateTimeField(auto_now_add=True)
    sold = models.BooleanField(default=False)

    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

CodePudding user response:

You are retrieving posts related to requested users and get_queryset() is expected request.user.id that's why you are getting error, if you want to allow everbody to see posts:

def get_queryset(self):
    return Post.objects.all().order_by('-created')
  • Related