django rest form无效错误

时间:2017-01-28 10:35:53

标签: django angular django-rest-framework

我有一个模型,模型表格和视图如下:

@api_view(['POST'])
def addCigar(request):
    print(request.POST)
    form = CigarForm()
    if request.POST:
        form = CigarForm(request.POST)
        if form.is_valid():
            cigar.save()
            cigar = Cigar.objects.filter(id=cigar.id)
            serializer = CigarSerializer(cigar, many=True)
            return Response(serializer.data)
        else:
            return Response("Form not valid, insert correct fields.")

形式:

class CigarForm(ModelForm):
    class Meta:
        model = Cigar
        fields = ['brand','origin','shape', 'strength', 'aroma', 'notes', 'rating', ]

型号:

class Cigar(models.Model):
    brand = models.CharField(max_length=50, blank=False,)
    origin = models.CharField(max_length=30, blank=False,)
    shape = models.CharField(max_length=20, blank=False,)
    strength = models.CharField(max_length=20, blank=False,)
    aroma = models.CharField(max_length=20, blank=False,)
    notes = models.CharField(max_length=100, blank=False,)
    rating = models.IntegerField(null=True, )

我的angular2前端服务:

public addCigar(

    brand: string, 
    origin: string,
    shape: string,
    strength: string,
    aroma: string, 
    notes: string, 
    rating: number) {

    console.log("In service")
    let obj = new CigarModel(brand, origin, shape, strength, aroma, notes, rating);

    let body = JSON.stringify(obj);
    console.log(body)

    let headers = new Headers({ 'Content-Type': 'application/json; charset=utf-8' });
    let options = new RequestOptions({ headers: headers });
    return this.http.post(this.myUrl + 'api/cigar/add/', body, options)
    .toPromise()
    .then(response => response.json())
}

然而,这给了我无效的错误。视图中的print语句打印<QueryDict: {}>,服务主体中的console.log打印{"brand":"Nitish","origin":"India","shape":"Thin","strength":"Strong","aroma":"Wood","notes":"Good","rating":"4"}

我在这里做错了什么?我的前端或后端有问题吗?

更新:而不是request.POST我现在正在使用request.data

1 个答案:

答案 0 :(得分:1)

关注this example

创建一个JSONResponse类

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)

您无需初始化表单来验证数据。这是json的内容。您需要使用序列化程序。

@api_view(['POST'])
def addCigar(request):
    if request.method == 'POST':
        serializer = CigarSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)