Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x053A7E68>

Viewed 1491

I'm trying to create a shopping cart api with django rest framework. I created my view and serializer and urls . but when I want to test my api with postman i have this error:

Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x053A7E68>.

I want to add a product to my cart. my authentication system is token authentication. I'll pass the token in the header of the request but still I have that error.

i will share my code here:

serializers

class OrderItemSerializer(serializers.ModelSerializer):
    product = serializers.SerializerMethodField()
    final_price = serializers.SerializerMethodField()

    class Meta:
        model = OrderItem
        fields = (
            'id',
            'product',
            'quantity',
            'final_price'
        )

    def get_product(self, obj):
        return ProductSerializer(obj.item).data

    def get_final_price(self, obj):
        return obj.get_final_price()


class OrderSerializer(serializers.ModelSerializer):
    order_items = serializers.SerializerMethodField()
    total = serializers.SerializerMethodField()

    class Meta:
        model = Order
        fields = (
            'id',
            'order_items',
            'total',
            'coupon'
        )

    def get_order_items(self, obj):
        return OrderItemSerializer(obj.products.all(), many=True).data

    def get_total(self, obj):
        return obj.get_total()

#views:

class AddToCartView(APIView):
    def post(self, request, *args, **kwargs):
        slug = request.data.get('slug', None)
        if slug is None:
            return Response({"message": "Invalid request"}, status=HTTP_400_BAD_REQUEST)
        product = get_object_or_404(Product, slug=slug)
        order_item, created = OrderItem.objects.get_or_create(
            product=product,
            user=request.user,
            ordered=False
        )
        order_qs = Order.objects.filter(user=request.user, ordered=False)
        if order_qs.exists():
            order = order_qs[0]
            # check if the order item is in the order
            if order.products.filter(product__slug=product.slug).exists():
                order_item.quantity += 1
                order_item.save()
                return Response(status=HTTP_200_OK)
            else:
                order.products.add(order_item)
                return Response(status=HTTP_200_OK)

        else:
            ordered_date = timezone.now()
            order = Order.objects.create(
                user=request.user, ordered_date=ordered_date)
            order.products.add(order_item)
            return Response(status=HTTP_200_OK)

#urls:

path('add_to_cart/', AddToCartView.as_view(), name='add_to_cart'),

this is the my postman: i pass the slug in the body and token in the authorization. enter image description here

rest framework:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        # 'rest_framework.authentication.SessionAuthentication',
    ],
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],
    'SEARCH_PARAM': 'q'
}

REST_AUTH_SERIALIZERS = {
    'LOGIN_SERIALIZER': 'Accounts.serializers.LoginUserSerializer',
}
1 Answers

I Believe the error is in your postman configuration. DRF token expects the header to look like:

Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b

But you have a postman set to Bearer type and also you token is surrounded by ""

Change it to: enter image description here And add it the token here: enter image description here

Related