无法使用JSON发送POST

时间:2015-01-10 17:20:23

标签: django django-rest-framework

我正在使用rest框架的django app工作。我需要通过json在表中添加一个新行,但是这个表是另一个表的子项。

当我尝试发送" POST"该应用程序返回此错误: ...可能不是NULL

图片> https://dl.dropboxusercontent.com/u/31258353/addnewrow.jpg

模型:

 # Create your models here.
    class sequence(models.Model):
        number = models.CharField(max_length=3)
        word = models.CharField(max_length=1)
        name = models.CharField(max_length=100)


    class localization(models.Model):
        sequence = models.ForeignKey(sequence)
        init = models.CharField(max_length=3)
        name = models.CharField(max_length=100)

FORM:

    class sequenceform(forms.ModelForm):
        class Meta:
            model = sequence


    class localizationform(forms.ModelForm):
        class Meta:
            model = localization

SERIALIZE:

class sequenceserializer(serializers.ModelSerializer):
    class Meta:
        model = sequence
        fields = ("pk","number","word","name")

class localizationserializer(serializers.ModelSerializer):
    class Meta:
        model = localization
        fields = ("id","init","name")

查看:

@api_view(['GET', 'POST'])
def sequencelistjson(request, format=None):
    if request.method == 'GET':
        prj = sequence.objects.all()
        serializer = sequenceserializer(prj, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = sequenceserializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', 'POST'])
def localizationlistjson(request, seq_id, format=None):
    if request.method == 'GET':
        seq = get_object_or_404(sequence, pk=seq_id)
        loc = seq.localization_set.order_by('init')
        serializer = localizationserializer(loc, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = localizationserializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)

1 个答案:

答案 0 :(得分:0)

您正在尝试创建localization对象,但它需要sequence存在(ForeignKey可见)。

在序列化程序中,您没有为sequence指定字段,因此Django REST框架不知道需要一个字段。因为您没有将sequence与其他地方相关联,所以当Django REST框架尝试创建localization对象时,sequence将作为NULL发送。这是不允许的,因为ForeignKey没有设置null=True(这是必需的)。

您可以通过将null=True添加到sequence字段来解决此问题(如果实际上并非如此)。另一个选项(很可能是您想要的)是在序列化程序的sequence选项中包含Meta.fields字段。