POST请求方法在Django Rest Framework中不起作用

时间:2018-12-17 18:02:15

标签: python django rest api django-rest-framework

每当我尝试发布请求时,这就是我得到的错误:

/ api /

中的

TypeError

禁止直接分配给多对多集的正面。改用project_team.set()。

请求方法:POST 要求网址:http://127.0.0.1:8000/api/ Django版本:2.0 异常类型:TypeError 异常值:

禁止直接分配给多对多集的正面。改用project_team.set()。

异常位置: set 中的C:\ Users \ Siddhesh \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ site-packages \ django \ db \ models \ fields \ related_descriptors.py, 509行 Python可执行文件:C:\ Users \ Siddhesh \ AppData \ Local \ Programs \ Python \ Python36 \ python.exe Python版本:3.6.3 Python路径:

['C:\ Users \ Siddhesh \ Desktop \ TechForSocial \ backend',  'C:\ Users \ Siddhesh \ AppData \ Local \ Programs \ Python \ Python36 \ python36.zip',  'C:\ Users \ Siddhesh \ AppData \ Local \ Programs \ Python \ Python36 \ DLLs',  'C:\ Users \ Siddhesh \ AppData \ Local \ Programs \ Python \ Python36 \ lib',  'C:\ Users \ Siddhesh \ AppData \ Local \ Programs \ Python \ Python36',  'C:\ Users \ Siddhesh \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ site-packages',  'C:\ Users \ Siddhesh \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ site-packages \ pytz-2018.5-py3.6.egg']

服务器时间:2018年12月17日星期一17:57:57

代码: Models.py

class DummyPeopleModel(models.Model):

    person_name = models.CharField(max_length=45)

    def __str__(self):

        return self.person_name


class ActiveProject(models.Model):

    project_name = models.CharField(max_length=30)
    project_abstract = models.CharField(max_length=1000)
    project_paper = models.CharField(max_length=1000)
    project_team = models.ManyToManyField(DummyPeopleModel, help_text='Team that works on this Project' )
    project_join_us = models.CharField(max_length=1000)

    def __str__(self):
        return self.project_name

serializers.py
from rest_framework import serializers
from .models import ActiveProject


class ActiveProjectSerializer(serializers.ModelSerializer):

    class Meta:

        model = ActiveProject
        fields = ('id', 'project_name', 'project_abstract', 'project_paper', 'project_team', 'project_join_us',)

    def create(self, validated_data):
        return ActiveProject.objects.create(**validated_data)

views.py
class ProjectList(generics.ListAPIView):
    queryset = ActiveProject.objects.all()
    serializer_class = ActiveProjectSerializer

    def post(self, request):

        serializer = ActiveProjectSerializer(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)


class ProjectDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = ActiveProject.objects.all()
    serializer_class = ActiveProjectSerializer

1 个答案:

答案 0 :(得分:0)

按照the documentation,在序列化程序中将project_team指定为PrimaryKeyRelatedField(many=True)可能会有所帮助(不过请不要将其设置为read_only