def post(self, request, *args, **kwargs): user = request.user data = request.data quiz = get_object_or_404(Quiz, pk=kwargs.get("pk")) question = { "description": data['question'], "quiz": quiz.pk, "owner": user.pk } serializer = QuestionSerializer(data=question) serializer.is_valid(raise_exception=True) serializer.save() choices = data['choices'] question = serializer.instance for c in choices: choice = { "description": c['text'], "is_answer": c['is_answer'], "question": question.pk, "owner": user.pk } serializer = ChoiceSerializer(data=choice) serializer.is_valid(raise_exception=True) serializer.save() return Response(QuestionDetailSerializer(question).data, status=HTTP_200_OK)
def put(self, request, *args, **kwargs): user = request.user data = request.data pk = kwargs['pk'] question = get_object_or_404(Question, pk=pk) if not question.is_authorized(request.user): return Response(status=401) question_data = { "owner": question.owner.pk, "description": data['question'], "last_edited_at": datetime.datetime.now(), "quiz": question.quiz.pk } serializer = QuestionSerializer(question, data=question_data) serializer.is_valid(raise_exception=True) serializer.save() choices = data['choices'] for c in choices: choice_data = { "description": c['text'], "is_answer": c['is_answer'], "question": question.pk, "owner": user.pk } if "id" in c: choice = Choice.objects.filter(pk=c['id']).first() if choice: serializer = ChoiceSerializer(choice, data=choice_data) else: serializer = ChoiceSerializer(data=choice_data) serializer.is_valid(raise_exception=True) serializer.save() return Response(QuestionDetailSerializer(question).data, status=HTTP_200_OK)
def put(self, request, quiz_pk, question_pk): question = self.get_object(quiz_pk, question_pk) serializer = QuestionSerializer(question, data=request.data, context={ 'request': request, 'quiz_pk': quiz_pk }) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, pk, format=None): """Create new question.""" quiz = self.get_object(pk) serializer = QuestionSerializer(data=request.data, context={ 'request': request, 'quiz_pk': quiz.pk }, many=True) 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)