R
R
reqww2020-06-15 13:45:05
React
reqww, 2020-06-15 13:45:05

How to accept POST data from react in django?

I'm trying to send the product id, quantity and user to django with react using a post request
Code for react:

const addItemToBasket = (item) => {
        dispatch({type: ADD_ITEM_TO_BASKET, payload: item})
        console.log(item.id, store.get('email'))
        axios.defaults.xsrfCookieName = 'csrftoken'
        axios.defaults.xsrfHeaderName = 'X-CSRFToken'
        axios.post("http://localhost:8000/cart/add", {
            uid: item.id, amount: 1, email: store.get('email')
        })
            .then((response) => {
                console.log(response.data)
            })
            .catch((error) => {
                console.log(error);
            });
    }


function in django
@csrf_exempt
def add_to_cart(request):
    print(request)
    email = request.POST.get('email', False)
    print(email)
    uid = request.POST.get('uid', False)
    print(uid)
    amount = request.POST.get('amount', False)
    print(amount)
    u = get_object_or_404(Account, email = email)
    p = Product.objects.get(id = uid)
    user_order = Order.get_or_create(owner = u)
    try:
        order_item = user_order.items.get(product = p)
        order_item.amount += amount
    except:
        order_item = user_order.items.create()
        order_item.amount = amount
        order_item.product = p
    order_item.save()
    
    user_order.total += p.price * amount
    ref_code = user.order.ref_code
    if ref_code == '':
        user_order.ref_code = generate_token(u.email)
    user.order.save()


As a result, I see the following in the console: 5ee751155e441110150325.png

What can be done to still transfer the data?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-06-15
@bacon

vovashaplin So you found a solution, or is it still not a solution? Well, a few accounts are prohibited by the rules. And on the question, learn the difference about passing data as www-form-urlencoded and as json in the body of the POST request.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question