def poll(request): if request.method == 'GET': questions = Question.objects.all() serializer = QuestionSerializer(questions, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': json_parser = JSONParser() data = json_parser.parse(request) serializer = QuestionSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400)
def test_update_authorized(text, type, status_code, api_client_as_admin): question = QuestionsFactory.create() question.text = text question.type = type data = QuestionSerializer(question).data response = api_client_as_admin.put(reverse(f'{base_url}-detail', kwargs={'pk': question.pk}), data=json.dumps(data), content_type='application/json') assert response.status_code == status_code if status_code == status.HTTP_200_OK: assert QuestionSerializer( Question.objects.get(pk=question.pk)).data == data
def post(self, request): question = Question() question.question_text = "the question is what?" question.pub_date = timezone.now() # 序列化方法1 serializer = QuestionSerializer(question) print(serializer.data) #反序列化 stream = io.BytesIO(JSONRenderer().render(serializer.data)) data = JSONParser().parse(stream) print(QuestionSerializer(data).data) return Response(serializer.data)
def create_question(request): if request.method == 'POST': data = JSONParser().parse(request) #take in json serializer = QuestionSerializer( data=data) #serialize the json into python object if serializer.is_valid(): #if the python object is valid new_question = Question.objects.create( question_text=serializer.data.get("question_text"), question_key=generate_key()) serializer = QuestionSerializer( new_question) #create the new question to return return JsonResponse(serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def test_get_question_by_valid_id(self): url = reverse('get_delete_question', kwargs={'pk': self.q1.pk}) response = self.client.get(url, format='json') serializer = QuestionSerializer(self.q1) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, serializer.data)
def get(self, request, pk): poll = Poll.objects.get(id=pk) question = Question.objects.filter(poll=poll).all() serializer = QuestionSerializer(question, many=True) if serializer: return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, pk, format=None): snippet = self.get_object(pk) serializer = QuestionSerializer(snippet, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def question_list(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': questions = Question.objects.all() serializer = QuestionSerializer(questions, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = QuestionSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400)
def test_get_single_valid(api_client, question_fixture): pk = question_fixture[0].pk expected = QuestionSerializer(Question.objects.get(pk=pk)).data url = reverse(f'{base_url}-detail', kwargs={'pk': pk}) response = api_client.get(url) assert response.status_code == status.HTTP_200_OK assert response.data == expected
def post(self, request, pk, format='json'): poll = Poll.objects.get(id=pk) serializer = QuestionSerializer(data=request.data) if serializer.is_valid(): question = serializer.save(poll=poll) if question: return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def question_detail(request, key): if request.method == 'GET': question = get_object_or_404(Question, question_key=key) serializer = QuestionSerializer(question) #turn question into json return Response(serializer.data) else: return Response(status=status.HTTP_404_NOT_FOUND)
def test_get_list_by_poll(api_client, question_fixture): poll_pk = question_fixture[0].poll.pk expected = QuestionSerializer(Question.objects.filter(pk=poll_pk), many=True).data url = reverse(f'{base_url}-list') response = api_client.get(url, data={'poll': poll_pk}) assert response.status_code == status.HTTP_200_OK assert response.data == expected
def test_unauthorized_update_question(api_client): question = QuestionsFactory.create() question_data = QuestionSerializer(question).data response = api_client.put(reverse(f'{base_url}-detail', kwargs={'pk': question.pk}), data=json.dumps(question_data), content_type='application/json') assert response.status_code == status.HTTP_401_UNAUTHORIZED
def test_get_user_questions_valid(self): url = reverse('questions_by_user', kwargs={'pk': self.user_1.pk}) response = self.client.get(url, format='json') questions = Question.objects.filter(owner=self.user_1) serializer = QuestionSerializer(questions, many=True) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(questions.count(), 2) self.assertEqual(response.data, serializer.data)
def question_list(request): if request.method == 'GET': questions = Question.objects.all() serializer = QuestionSerializer( questions, many=True) #serialize many questions into one json object return Response(serializer.data) else: return Response(status=status.HTTP_404_NOT_FOUND)
def test_get_questions(self): """ Get all questions """ url = reverse('questions') response = self.client.get(url, format='json') questions = Question.objects.all() serializer = QuestionSerializer(questions, many=True) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, serializer.data)
def get_questions_with_given_tag(self, request, pk=None): ''' GET /tags/{pk}/questions ''' tag = get_object_or_404(self.queryset, pk=pk) data = tag.question_set.all() seralizer = QuestionSerializer(data, many=True) return HTTP_Response( { 'status': 'success', 'length': len(seralizer.data), 'questions': seralizer.data }, 200)
def retrieve(self, request, pk=None, poll_pk=None): try: poll = Poll.objects.get(id=poll_pk) except ObjectDoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if not poll.questions.filter(id=pk).exists(): return Response("question id %s not associated with Poll %s " % (pk, poll_pk), status=status.HTTP_400_BAD_REQUEST) question = poll.questions.get(id=pk) return Response(QuestionSerializer(question).data)
def test_list_questions(self, questions: typing.List[Question], poll: Poll): path = reverse('polls:question-list') request = self.factory.get(path, data={'poll_id': poll.id}) response = QuestionViewSet.as_view({'get': 'list'})(request) assert response.status_code == 200 assert response.data == QuestionSerializer(questions, many=True).data request = self.factory.get(path) response = QuestionViewSet.as_view({'get': 'list'})(request) assert response.status_code == 400
def poll_details(request, pk): try: instance = Question.objects.get(id=pk) except Question.DoesNotExist as e: return JsonResponse({'error': 'Question objects is DoseNotExist'}, status=404) if request.method == 'GET': serializer = QuestionSerializer(instance=instance) return JsonResponse(serializer.data, status=200) if request.method == 'PUT': json_parser = JSONParser() data = json_parser.parse(request) serializer = QuestionSerializer(instance, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=200) return JsonResponse(serializer.errors, status=400) if request.method == 'DELETE': instance.delete() return JsonResponse({'messgae': 'Objects is delete'}, status=204)
def create(self, request, **kwargs): try: poll = Poll.objects.get(id=kwargs.get('poll_pk')) except ObjectDoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) request.data.update(poll=poll) serializer = QuestionSerializer(data=request.data) if serializer.is_valid(): inst = serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, *args, **kwargs): question_pk = kwargs.get('pk', None) questions = Question.objects.filter(pk=question_pk) payload = request.data if questions.exists(): question = questions.first() choice_pk = payload.get('choice', None) possible_choices = question.choice_set.filter(pk=choice_pk) if possible_choices.exists(): choice = possible_choices.first() choice.votes += 1 choice.save() serializer = QuestionSerializer(question) print(serializer.data) return response.Response(serializer.data, status=status.HTTP_200_OK) return response.Response('Not a valid choice or question', status=status.HTTP_400_BAD_REQUEST)
def update(self, request, pk=None, poll_pk=None): try: poll = Poll.objects.get(id=poll_pk) except ObjectDoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if not poll.questions.filter(id=pk).exists(): return Response("question id %s not associated with Poll %s " % (pk, poll_pk), status=status.HTTP_400_BAD_REQUEST) question = poll.questions.get(id=pk) request.data.update(poll=poll) serializer = QuestionSerializer(question, data=request.data) if serializer.is_valid(): inst = serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, format=None): serializer = QuestionSerializer(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)
def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) instance = serializer.save() return response.Response(QuestionSerializer(instance).data, status=status.HTTP_201_CREATED)
class PollSerializer(EntitySerializer): class Meta: model = Poll fields = ('id', 'description', 'questions', 'user_state', 'num_responders', 'created', 'event', 'entity_state') read_only_fields = ( 'entity_state', 'num_responders', 'created', 'event', ) event = serializers.SerializerMethodField() questions = QuestionSerializer(many=True) def get_user_state(self, obj): return "" def prepare(self, validated_data): self.questions = validated_data.pop('questions', None) super(PollSerializer, self).prepare(validated_data) def post_create_update(self, obj, update=False): for q in self.questions: choices = q.pop('choices', []) q_inst = Question.objects.create(poll=obj, **q) cls = Question.objects.get_choice_cls_from_type(q['question_type']) if choices: [cls.objects.create(question=q_inst, **c) for c in choices] else: cls.objects.create(question=q_inst) super(PollSerializer, self).post_create_update(obj, update=update) def create(self, validated_data, **kwargs): validated_data.update(entity_type=BaseEntityComponent.POLL) self.prepare(validated_data) obj = super(PollSerializer, self).create(validated_data) self.post_create_update(obj) return obj def update(self, instance, validated_data): self.prepare(validated_data) super(PollSerializer, self).update(instance, validated_data) # clear all questions first. For some reason bulk delete is not working for q in instance.questions.all(): q.delete() # create the questions and choices self.post_create_update(instance, update=True) return instance def get_event(self, obj): event = obj.get_parent_entities_by_contenttype_id( ContentType.objects.get(model="event")) return EventSerializerL0(event, many=True).data
def get(self, request, format=None): questions = Question.objects.all() serializer = QuestionSerializer(questions, many=True) return Response(serializer.data)
def get(self, request, pk, format=None): question = self.get_object(pk) serializer = QuestionSerializer(question) return Response(serializer.data)
def get(self, request, pk, format=None): user = self.get_user(pk) questions = Question.objects.filter(owner=user) serializer = QuestionSerializer(questions, many=True) return Response(serializer.data)
def question_collection(request): if request.method == 'GET': question = Question.objects.all() serializer = QuestionSerializer(question, many=True) return Response(serializer.data)