why getting 'WSGIRequest' object has no attribute 'data' error?

Viewed 778

I am trying to use card payment through stripe in react Js and Django. I am following https://betterprogramming.pub/how-to-integrate-django-react-app-with-stripe-payments-95709b3f23e5 this tutorial.

frontend

const handleSubmit = async (event) => {
    event.preventDefault();
    const card = elements.getElement(CardElement);
    const {paymentMethod, error} = await stripe.createPaymentMethod({
      type: 'card',
      card: card
  });
  ApiService.saveStripeInfo({
    email, payment_method_id: paymentMethod.id})
  .then(response => {
    console.log(response.data);
  }).catch(error => {
    console.log(error)
  })
}
export const api = axios.create({
  baseURL: API_URL,
  headers: {
    "Content-type": "application/json"
  }
});
export default class ApiService{
  static saveStripeInfo(data={}){
    return api.post(`${API_URL}/payments/save-stripe-info/`, data)
  }
}

server

@api_view(['POST'])
def test_payment(request):
    test_payment_intent = stripe.PaymentIntent.create(
    amount=1000, currency='pln', 
    payment_method_types=['card'],
    receipt_email='test@example.com')
    return Response(status=status.HTTP_200_OK, data=test_payment_intent)
        
def save_stripe_info(request):
    print('this => ',request.data)
    data = request.data
    email = data['email']
    payment_method_id = data['payment_method_id']
    
    # creating customer
    customer = stripe.Customer.create(
      email=email, payment_method=payment_method_id)
     
    return Response(status=status.HTTP_200_OK, 
      data={
        'message': 'Success', 
        'data': {'customer_id': customer.id} 
      }  
    )       

but whenever I click the submit button it given me following error

AttributeError: 'WSGIRequest' object has no attribute 'data' [12/Dec/2021 21:55:57] "POST /payments/save-stripe-info/ HTTP/1.1" 500 71355

for full code please visit https://betterprogramming.pub/how-to-integrate-django-react-app-with-stripe-payments-95709b3f23e5

2 Answers

According to the docs there is no data member of WSGIRequest. You will need to refer to the body attribute instead.

data is part of the rest_framework. You need to decorate the view with an api_view.

Just add "@api_view(['POST'])" before the def save_stripe_info(request). It should be:

@api_view(['POST'])
def save_stripe_info(request):
    print('this => ',request.data)
    data = request.data
    email = data['email']
    payment_method_id = data['payment_method_id']
    
    # creating customer
    customer = stripe.Customer.create(
      email=email, payment_method=payment_method_id)
     
    return Response(status=status.HTTP_200_OK, 
      data={
        'message': 'Success', 
        'data': {'customer_id': customer.id} 
      }  
    )  

or just load the body in json.

data = json.loads(request.body)
Related