在Django REST中向API发布查询

时间:2017-07-25 19:41:58

标签: django angular rest django-rest-framework

我在Angular 2中有代码:

sendPost(){
    let headers = new Headers();
      headers.append('Content-Type', 'application/json');

    let requestOptions = new RequestOptions({headers: headers});
    requestOptions.headers = headers;

      let data = {
                  "name": "XX", 
                  "email": "xxx@op.com", 
                  "phone_number": "+99999995555", 
                  "address": "YYY", 
                  "code": "80-885", 
                  "city": "YHYY", 
                  "voivodeship": "ZZZZ", 
                  "description": "VVVVV"
                  };

        this.http.post(`http://127.0.0.1:8000/companies/create`, data, requestOptions).subscribe(res => {
            console.log(res.json());
          }, (err) => {
            console.log(err);
          });
  }

错误API:

<WSGIRequest: OPTIONS '/companies/create'>
Internal Server Error: /companies/create
Traceback (most recent call last):
  File "C:XX\CRM\env\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "C:XX\CRM\env\lib\site-packages\django\core\handlers\base.py", line 198, in _get_response
    "returned None instead." % (callback.__module__, view_name)
ValueError: The view my_crm.views.companies_create didn't return an HttpResponse object. It returned None instead.
[25/Jul/2017 21:32:35] "OPTIONS /companies/create HTTP/1.1" 500 59515

API显示函数中某处有错误,但是当我使用POSTMAN时,这是相同的JSON,没有问题。哪里可以出错? 我认为在使用POSTMAN进行测试时,API处理得很好。

修改 API函数:

@csrf_exempt
def companies_create(request):
    """
    Create a new company.
    """
    if request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = CompanySerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

1 个答案:

答案 0 :(得分:0)

解决方案是替换:

headers.append('Content-Type', 'application/json');

为:

headers.append('Content-Type', 'application/x-www-form-urlencoded');

我无法解释这个,因为我正在发送一个JSON文件。也许有人会解释这是关于什么的?