Пример #1
0
    def save_question_data(data):
        serializer = QuestionSerializer(data=data)

        if serializer.is_valid():
            try:
                question = serializer.save()
                # Save Question Choices
                for i in range(1, 5):
                    question_choice_get = "question_choice_" + str(i)
                    choice_img_url = "question_choice_" + str(i) + "_image_url"
                    if i == int(data.get("correct_choice")):
                        QuestionChoice.objects.create(
                            choice_text=data.get(question_choice_get),
                            choice_img_url=data.get(choice_img_url),
                            is_right_choice=True,
                            question=question
                        )
                    else:
                        QuestionChoice.objects.create(
                            choice_text=data.get(question_choice_get),
                            choice_img_url=data.get(choice_img_url),
                            question=question
                        )
                # Save Question Chapter Mapping
                QuestionChapterMapping.objects.create(question=question, chapter_id=data.get("chapter_id"))

                return Response(serializer.data, status=status.HTTP_201_CREATED)
            except Exception as err:
                print("Exception occurred in Question Post \n", err)
                return Response(status=status.HTTP_400_BAD_REQUEST)
        print("Exception in Question Post\n", serializer.errors)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Пример #2
0
 def test_question_deserializer_valid_json(self):
     question_json = '{"id": 2, "question_text": "text", "question_catalogue": 1}'
     stream = BytesIO(question_json)
     data = JSONParser().parse(stream)
     serializer = QuestionSerializer(data=data)
     self.assertTrue(serializer.is_valid())
     question = serializer.object
     question.save()
     #
     question_from_db = Question.objects.get(pk=2)
     self.assertEqual(question.question_text, "text")
     self.assertEqual(question_from_db.question_text, "text")
     #
     self.assertTrue(type(question.question_catalogue) is QuestionCatalogue)
     self.assertEqual(question.question_catalogue.pk,
                      self.question_catalogue.pk)
     self.assertEqual(question.question_catalogue.catalogue_name,
                      self.question_catalogue.catalogue_name)
     #
     self.assertTrue(
         type(question_from_db.question_catalogue) is QuestionCatalogue)
     self.assertEqual(question_from_db.question_catalogue.pk,
                      self.question_catalogue.pk)
     self.assertEqual(question_from_db.question_catalogue.catalogue_name,
                      self.question_catalogue.catalogue_name)
Пример #3
0
 def test_expected_fields(self):
     """Tests expected serializer fields
     'title',
     'body'
     """
     question_data = factory.build(dict, FACTORY_CLASS=QuestionFactory)
     serializer = QuestionSerializer(data=question_data)
     is_valid = serializer.is_valid()
     print("Keys: ", serializer.validated_data.keys())
     print("Errors: ", serializer.errors)
     assert is_valid, "serializer validation test"
     assert serializer.validated_data.keys() == set(['title', 'body'])
Пример #4
0
def question_answer_detail(request, pk):
    try:
        question = Question.objects.get(pk=pk)
    except Question.DoesNotExist:
        return HttpResponse(status=status.HTTP_404_NOT_FOUND)
    if request.method == 'GET':
        question_serializer = QuestionSerializer(question)
        return JSONResponse(question_serializer.data)
    elif request.method == 'PUT':
        question_data = JSONParser().parse(request)
        question_serializer = QuestionSerializer(question, data=question_data)
        if question_serializer.is_valid():
            question_serializer.save()
            return JSONResponse(question_serializer.data)
        return JSONResponse(question_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        question.delete()
        return HttpResponse(status=status.HTTP_204_NO_CONTENT)
Пример #5
0
def question_answer_list(request):
    if request.method == 'GET':
        questions = Question.objects.all()
        questions_serializer = QuestionSerializer(questions, many=True)
        answers = Answer.objects.all()
        answers_serializer = AnswerSerializer(answers, many=True)
        json_response = {
            'questions': questions_serializer.data,
            'answers': answers_serializer.data,
        }
        return JSONResponse(json_response)
    elif request.method == 'POST':
        question_data = JSONParser().parse(request)
        question_serializer = QuestionSerializer(data=question_data)
        if question_serializer.is_valid():
            question_serializer.save()
            return JSONResponse(question_serializer.data,
                                status=status.HTTP_201_CREATED)
        return JSONResponse(question_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Пример #6
0
    def create(self, request, *args, **kwargs):
        try:
            items_data = request.data['items']
        except KeyError:
            return response.Response({"questions": "not exists"},
                                     status=status.HTTP_400_BAD_REQUEST)

        serializer = self.get_serializer(data=request.data)
        if not serializer.is_valid():
            return response.Response({"test serializer": "error"},
                                     status=status.HTTP_400_BAD_REQUEST)

        with transaction.atomic():
            serializer.save()
            for item in items_data:
                s = QuestionSerializer(data=item)
                if not s.is_valid():
                    return response.Response({"question serializer": "error"},
                                             status.HTTP_400_BAD_REQUEST)
                s.save()
        return response.Response(serializer.data,
                                 status=status.HTTP_201_CREATED)
Пример #7
0
 def test_question_catalogue_invalid_scope(self):
     catalogue_json = '{"id": 2, "catalogue_scope": "wrong", "catalogue_name": "cat"}'
     stream = BytesIO(catalogue_json)
     data = JSONParser().parse(stream)
     question_catalogue_serializer = QuestionSerializer(data=data)
     self.assertFalse(question_catalogue_serializer.is_valid())
Пример #8
0
 def test_question_deserializer_invalid_json(self):
     question_json = '{"question_catalogue": 1}'
     stream = BytesIO(question_json)
     data = JSONParser().parse(stream)
     serializer = QuestionSerializer(data=data)
     self.assertFalse(serializer.is_valid())
Пример #9
0
content = JSONRenderer().render(serializer.data)
content
# '{"pk":3,"title":"Do you afraid from snakes?","description":""}'





# Deserialization is similar. First we parse a stream into Python native datatypes...
from django.utils.six import BytesIO
from rest_framework.parsers import JSONParser
stream = BytesIO(content)
data = JSONParser().parse(stream)
# ...then we restore those native datatypes into a fully populated object instance.
serializer = QuestionSerializer(data=data)
serializer.is_valid()
# True
serializer.validated_data
# OrderedDict([('title', ''), ('code', 'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])
serializer.save()
# <Snippet: Snippet object>



# get all data
serializer = QuestionSerializer(Question.objects.all(), many=True)



# One nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing its representation.
from questions.serializers import QuestionSerializer
Пример #10
0
 def create(self, request, *args, **kwargs):
     serializer = QuestionSerializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     serializer.save()
     return response.Response(serializer.data,
                              status=status.HTTP_201_CREATED)