3
votes

I'm trying to post json data to my Django Rest Framework APIView. All works well when I use the DRF api post form, but when I try with an external app (Angular2 in my case), the request.data variable is empty.

My APIView:

class CreatePaymentView(views.APIView):

    def post(self, request, *args, **kwargs):
        print(request.data)
        return None

My urls:

url(r'payment/create', views.CreatePaymentView.as_view(), name='CreatePayment'),

My Angular2 post:

createPayment(): Observable<any> {
     let body = JSON.stringify({test_data: 'whatever'});

    let headers = new Headers({
      'Content-Type': 'application/json',
      'X-CSRFToken': this.cookiesService.csrftoken,
      'Authorization': `Token ${this.logged.user.token}`
    });
    let options = new RequestOptions({ headers: headers });
     return this.http.post(environment.server_url_api + 'payment/create/', body, options)
        .map(response => {
          return response;
        });
  }

All the other posts of my app works well, but all my other views are DRF ModelViewSet, that's why I tink that my bug doesn't come from the CRFs. I suspect something is bad with my django view.

When I read the request variable in my CreatePaymentView, the data is an empty JSON instead of {test_data: 'whatever'}.

What is the good practice to send a simple POST with DRF ?

1
Could you debug the request in your browser's network tab? Maybe the problem's there, since everything seems fine in your backend code. - lucasnadalutti
Thank you @lucasnadalutti for your comment. It appears that the problem comes from the Visual Studio watch feature with breakpoint. Without watching the code with breakpoint, all works fine. - Ben

1 Answers

0
votes

As explained in comments, it appears that the problem comes from the Visual Studio watch feature with breakpoint. Without watching the code with breakpoint, all works fine.