Answer the question
In order to leave comments, you need to log in
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);
});
}
@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()
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question