简体   繁体   中英

Unable to add Items to cart

I'm using django and react to build a simple checkout system. When I click on the add to cart button I get 404 page not found but the click event is supposed to add item to the cart instead of rendering a page. I'm not sure whether my function for the onclick event is accurate in the programme below. I'm finding great difficulty trying to figure out why I'm not able to add Items to the cart by clicking on the cart button using onClick event. The url on the console is pointing to the actual url containing the id of the element I'm trying to add. I can see the the error in both the browser console and Django server on the terminal. I don't know whether the error is with the react app or Django.

urls.py (Django)
path('add-to-cart/', add_to_cart_view.as_view(), name='add-to-cart'),


The react component 

const AddToCartURL = "http://127.0.0.1:8000";

const ProductDetails = (props) => {
    const [product, setProduct] = useState({});

    useEffect(() => {
        const id = props.match.params.id;
        const fetchData = async () => {
            try {
                const res = await axios.get(`${ProductDetailURL}/product/${id}`);
                setProduct(res.data);
                console.log(res.data)
            }
            catch (err) {

            }
        };

        fetchData();
    }, [props.match.params.id]);

    const handleAddToCartURL = (id) =>{
        const fetchData = async () => {
            try {
                const res = await axios.post(`${AddToCartURL}/add-to-cart/${id}`);
                setProduct(res.data);
                console.log(res.data)
            }
            catch (err) {

            }
        };

        fetchData();
    }

    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

And the Django programme for add to cart is:

class add_to_cart_view(APIView):
    def post(self, request, *args, **kwargs):
        id = request.data.get('id', None)
        if id is None:
            return Response({"message": "Invalid request. Ensure ypu have added added products to the cart"}, status=HTTP_400_BAD_REQUEST)

        product = get_object_or_404(Product, id=id)

        order_product_qs = product.objects.get_or_create(
            product=product,
            user=request.user,
            ordered=False
        )
        
        if order_product_qs.exists():
            order_product = order_product_qs.first()
            order_product.quantity += 1
            order_product.save()
        else:
            order_product = 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=order_product_qs.id).exists():
                order.products.add(order_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)

Thanks for updating. To send query parameters to add_to_cart you need to use a question mark instead of a slash:

`${AddToCartURL}/add-to-cart?${id}`

You can access the parameters within add_to_cart_view using:

request.query_params

DRF recommends using this instead of djangos request.GET ( https://www.django-rest-framework.org/api-guide/requests/#query_params )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM