为什么我在/ evaluationtest /上收到此错误KeyError? '请求'

时间:2019-04-08 08:25:56

标签: django django-rest-framework

嗨,我已经创建了一个Crud函数用于评估测试,但是我收到keyerror'request'对我来说很奇怪,在我不熟悉django之前还没有看到此错误,有人可以帮助我修复它吗?

def validate(self, data, *args, **kwargs):
        questions = self.context['request'].data.get("questions")
        if not questions:
            raise serializers.ValidationError("questions are required")
            if self.context["request"].method == "POST":
                self.questions = QuestionSerializer(data=questions, many=True)
                self.questions.is_valid(raise_exception=True)
            elif self.context["request"].method == "PUT":
                self.questions = questions
                self.new_questions = self.context["request"].data.get(
                    "new_questions")
                if self.new_questions:
                    self.new_questions = QuestionSerializer(
                        data=self.new_questions, many=True)
                    self.new_questions.is_valid(raise_exception=True)
            return data

    def create(self, data):
        evaluation_test = EvaluationTest()
        evaluation_test.category = data['category']
        evaluation_test.admin = data['admin']
        evaluation_test.title = data['title']
        evaluation_test.type = data['type']
        evaluation_test.save()

        for question in data['questions']:
            question.evaluationtest = evaluation_test
            question.save()
        return evaluation_test

    def update(self, instance, validated_data):
        instance.title = validated_data.get["title", instance.title]
        instance.type = validated_data.get["type", instance.type]
        instance.category = validated_data.get["category", instance.category]
        instance.admin = validated_data.get["admin", instance.admin]

        for question in self.questions:
            q = QuestionSerializer(instance=question["id"], data=question)
            q.is_valid(raise_exception=True)
            q.save()

        if self.new_questions:
            new_questions = self.new_questions.save()
            for question in new_questions:
                question.save()
        return instance

views.py 当我实现您可以看到的整个crud应用程序时,这是我的view.py代码,请告诉我如何进行修改以使其正常工作

class EvaluationTestViewSet(viewsets.ModelViewSet):

permission_classes = (IsAuthenticated, )
serializer_class = EvaluationTestSerializer
queryset = EvaluationTest.objects.all()

@action(methods=['get'], detail=False, url_path='by-category/(?P<category_id>\d+)', url_name='by_category')
def by_category(self, request, *args, **kwargs):
    evaluationtest = EvaluationTestSerializer.by_category(
        kwargs['category_id'])
    if evaluationtest:
        return Response(evaluationtest)
    return Response(status=HTTP_404_NOT_FOUND)

def create(self, request):
    serializer = EvaluationTestSerializer(data=request.data)
    if serializer.is_valid():
        evaluationtest = serializer.create(request)
        print(evaluationtest)
        if evaluationtest:
            return Response(status=HTTP_201_CREATED)
    return Response(status=HTTP_400_BAD_REQUEST)

1 个答案:

答案 0 :(得分:0)

您必须在序列化程序上下文中设置请求。

更改您的创建方法:

def create(self, request):
    serializer = EvaluationTestSerializer(data=request.data, context={'request': request})
    if serializer.is_valid():
        # call save() instead of create
        evaluationtest = serializer.save()
        print(evaluationtest)
        # ideally you should also return serializer.data
        return Response(status=HTTP_201_CREATED)
    # ideally you should also return serializer.errors
    return Response(status=HTTP_400_BAD_REQUEST)