I'm trying to create a simple shopping cart with django and react. When I click on the add-to-cart button I get 500 Internal Server Error
from react. The error it's displaying in django is:
ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x00000268F76AEFA0>": "order_product.user" must be a "User" instance.
I have tried every means I know but I'm still not able to fix it. Below is the programme:
DJANGO
urls.py
path('add-to-cart/', add_to_cart_view.as_view(), name='add-to-cart'),
views.py
class add_to_cart_view(APIView):
permission_classes = []
def post(self, request, *args, **kwargs):
id = request.data.get('id', None)
if id is None:
return Response({"message": "Invalid request"}, status=HTTP_400_BAD_REQUEST)
product = get_object_or_404(Product, id=id)
requested_product = order_product.objects.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]
if not order.products.filter(product__id=requested_product.id).exists():
order.products.add(requested_product)
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_product)
return Response(status=HTTP_200_OK)
REACT
export const AddToCartURL = "http://127.0.0.1:8000";
const handleAddToCartURL = async (id) => {
try {
const res = await axios.post(`${AddToCartURL}/add-to-cart/`, {id});
setProduct(res.data);
console.log(res.data)
}
catch (err) {
}
};
return(
<Box sx={{ flexGrow: 1 }} m={4}>
<Grid container spacing={3}>
<Grid item xs={9}>
<Item>
<img src={product.image} alt="" />
<div>
<p>{product.description}</p>
<p>{product.label}</p>
<p>{product.price}</p>
</div>
<button color='primary' onClick={() => handleAddToCartURL(product.id)}>
<AddShoppingCartIcon />
</button>
</Item>
</Grid>
<Grid item xs>
<Item>Similar Products</Item>
</Grid>
</Grid>
</Box>
)
}
export default ProductDetails
I really dont't understand why it is returning anonymous user from django. Please how do I fix it?
CodePudding user response:
You have this error because the user you try to assign is not authenticated. Add a permission to your view like this :
from rest_framework import permissions
class add_to_cart_view(APIView):
permission_classes = [permissions.IsAuthenticated]
# Rest of the code here
NB : You will need to authenticate the user before make a post request.
UPDATE : If you want to test with non authenticated user. You can create a generic user for that :
# Create a user with a name unauthenticated_user in the admin
# In the view :
if request.user.is_authenticated:
# Do something for authenticated users.
# Your code previous code here
else:
# retrieve the unauthenticated_user you create
# use your custom user here