带REST Framework的Python / Django - POST错误{“non_field_errors”:[“无效数据”]}

时间:2014-04-06 15:38:28

标签: python django django-models django-views django-rest-framework

我刚刚开始使用Django和REST Framework,并且在尝试发布实体时遇到错误。错误是: {" non_field_errors":["数据无效"]} 。这发生在 serializer.is_valid()

这是我的视图类:

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from API.models import Payload
from API.serializers import PayloadSerializer
from API.services import PayloadService


class JSONResponse(HttpResponse):
    """
    An HttpResponse that renders its content into JSON.
    """

    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)


    @csrf_exempt
    def payload_list(request):


        if request.method == 'POST':

            model = Payload(code="754d", body="Hello World")

            serializer = PayloadSerializer(data=model)

            if serializer.is_valid():
                serializer.save()
                return JSONResponse(serializer.data, status=201)
    return JSONResponse(serializer.errors, status=400)

以下是我的Payload模型供参考:

from __future__ import unicode_literals
from sqlserver_ado.fields import BigAutoField
from django.db import models


class Payload(models.Model):
    id = BigAutoField(db_column='Id', primary_key=True) # Field name made lowercase.
    code = models.CharField(db_column='Code', max_length=10) # Field name made lowercase.
    body = models.TextField(db_column='Body') # Field name made lowercase.
    class Meta:
        managed = False
        db_table = 'Payload'


值得注意的是,如果我正确设置视图并实际传入Json Payload对象作为请求的一部分,它就可以正常工作。

使用JSON有效负载:{"code": "NPMC", "body": "Hello World"}

工作视图代码:

if request.method == 'POST':

    data = JSONParser().parse(request)

    serializer = PayloadSerializer(data=data)

    if serializer.is_valid():
        serializer.save()
        return JSONResponse(serializer.data, status=201)
    return JSONResponse(serializer.errors, status=400)

回复:{"id": 25, "code": "NPMC", "body": "Hello World"}

1 个答案:

答案 0 :(得分:0)

好的,我能够通过使用Djangos找到解决问题的方法model_to_dict

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from API.models import Payload
from API.serializers import PayloadSerializer
from API.services import PayloadService
from django.forms.models import model_to_dict



class JSONResponse(HttpResponse):
    """
    An HttpResponse that renders its content into JSON.
    """

    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)


@csrf_exempt
def payload_list(request):

    if request.method == 'POST':

        model = Payload(code="754d", body="Hello World")

        result = model_to_dict(model, fields=[], exclude=[])

        serializer = PayloadSerializer(data=result)

        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)