스펙업/멋쟁이사자처럼

[홈페이지 제작] 장고 백엔드 API 설정 - 질문 기능

성밍쟁 2023. 12. 24. 21:14
728x90
반응형

질문 답변 게시판

(1) 질문 조회

localhost:8000/questions/     -> GET요청

class QuestionViewSet(viewsets.ModelViewSet):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer
    # permission_classes = [permissions.IsAuthenticatedOrReadOnly]  # 로그인한 사용자만 수정 가능하게

 

 

(2) 질문 생성

localhost:8000/question/   -> POST 요청

    def create(self, request, *args, **kwargs):
        # 클라이언트로부터 받은 데이터
        data = request.data

        # 클라이언트에서 제공한 student_id를 사용하여 User 객체를 찾습니다.
        student_id = data.get('student_id')
        try:
            user = User.objects.get(student_id=student_id)
        except User.DoesNotExist:
            return Response({"error": "User with the given student_id does not exist."},
                            status=status.HTTP_404_NOT_FOUND)

        # 새 Question 객체를 생성하고 User 객체를 연결합니다.
        question = Question(title=data.get('title'), content=data.get('content'), author=user)

        # Question 객체를 저장합니다.
        question.save()

        # 저장된 Question 객체의 정보를 반환합니다.
        return Response({"message": "Question created successfully", "question": {
            "title": question.title,
            "content": question.content,
            "student_id": user.student_id,
            "created_at": question.created_at,
        }}, status=status.HTTP_201_CREATED)

요청 시

다음과 같이 넘겨주면 됨

정상 실행이 된 모습.

 

 

 

(3) 질문 삭제

localhost:8000/question/번호/   -> DELETE 요청

9번 항목에 20201738이 입력한 글을 지울 예정

    def destroy(self, request, *args, **kwargs):
        student_id = request.data.get('student_id')  # 프론트엔드에서 전송한 student_id

        try:
            # student_id를 사용하여 User 객체 찾기
            user = User.objects.get(student_id=student_id)
        except User.DoesNotExist: #User 객체 존재하지 않다면?
            return Response({"error": "User not found."}, status=status.HTTP_404_NOT_FOUND)

        try:
            # URL에서 제공된 pk를 사용하여 Question 객체를 찾기
            question = Question.objects.get(pk=kwargs['pk'])
        except Question.DoesNotExist:
            return Response({"error": "Question not found."}, status=status.HTTP_404_NOT_FOUND)

        print(question)
        print(user)
        # User가 Question의 작성자와 일치하는지 확인
        if question.author == user:
            question.delete()  # 조건이 충족되면 질문을 삭제
            return Response({"message": "Question deleted successfully"}, status=status.HTTP_204_NO_CONTENT)
        else:
            # 작성자가 일치하지 않으면 오류 메시지를 반환
            return Response({"error": "You do not have permission to delete this question."},
                            status=status.HTTP_403_FORBIDDEN)

코드는 위와 같고

실행 결과 정상적으로 됨

 

 

(4) 글 상세 목록 조회

http://localhost:8000/qna/questions/<질문 번호>/  -> GET

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        answers = Answer.objects.filter(question=instance)
        serializer = self.get_serializer(instance)
        data = serializer.data
        data['answers'] = AnswerSerializer(answers, many=True).data
        return Response(data)

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

12/25일 추가 내용

(5) 모델 수정

class Question(models.Model):
    # 질문 제목
    title = models.CharField(max_length=200, verbose_name='제목')
    # 질문 내용
    content = models.TextField(verbose_name='내용')
    # 작성자는 장고의 내장 User 모델을 외래키로 사용
    author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='작성자', related_name='questions')
    # 생성 시간
    created_at = models.DateTimeField(default=timezone.now, verbose_name='생성 시간')
    modified_at = models.DateTimeField(null = True, blank = True)
    class Meta:
        verbose_name = 'QnA'
        verbose_name_plural = 'QnA'

    def __str__(self):
        return self.title

수정 기능을 넣기 위해서 수정 시간 추가

 

(6) 질문 수정

http://localhost:8000/qna/questions/<질문 번호>/  -> PUT

    def update(self, request, *args, **kwargs):
        # 클라이언트로부터 받은 데이터
        data = request.data

        # 클라이언트에서 제공한 student_id를 사용하여 User 객체를 찾습니다.
        student_id = data.get('student_id')
        try:
            user = User.objects.get(student_id=student_id)
        except User.DoesNotExist:
            return Response({"error": "주어진 학번을 가진 사용자가 존재하지 않습니다."},
                            status=status.HTTP_404_NOT_FOUND)

        # URL에서 제공된 question_id를 사용하여 해당 질문을 찾기
        question_id = kwargs.get('pk')
        try:
            question = Question.objects.get(pk=question_id)
        except Question.DoesNotExist:
            return Response({"error": "질문을 찾을 수 없습니다."},
                            status=status.HTTP_404_NOT_FOUND)

        # 질문 작성자와 현재 사용자가 일치하는지 확인
        if question.author == user:
            # 권한이 있는 경우 질문 내용 업데이트
            question.title = data.get('title')
            question.content = data.get('content')
            question.modified_at = timezone.now()  # modified_at 필드 업데이트
            question.save()
            return Response({"message": "질문이 성공적으로 수정되었습니다."}, status=status.HTTP_200_OK)
        else:
            # 작성자가 일치하지 않으면 오류 메시지를 반환
            return Response({"error": "이 질문을 수정할 권한이 없습니다."},
                            status=status.HTTP_403_FORBIDDEN)

 

 

전체 코드

class QuestionViewSet(viewsets.ModelViewSet):
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer
    # permission_classes = [permissions.IsAuthenticatedOrReadOnly]  # 로그인한 사용자만 수정 가능하게

    # 질문 생성

    def create(self, request, *args, **kwargs):
        # 클라이언트로부터 받은 데이터
        data = request.data

        # 클라이언트에서 제공한 student_id를 사용하여 User 객체를 찾습니다.
        student_id = data.get('student_id')
        try:
            user = User.objects.get(student_id=student_id)
        except User.DoesNotExist:
            return Response({"error": "User with the given student_id does not exist."},
                            status=status.HTTP_404_NOT_FOUND)

        # 새 Question 객체를 생성하고 User 객체를 연결합니다.
        question = Question(title=data.get('title'), content=data.get('content'), author=user)

        # Question 객체를 저장합니다.
        question.save()

        # 저장된 Question 객체의 정보를 반환합니다.
        return Response({"message": "Question created successfully", "question": {
            "title": question.title,
            "content": question.content,
            "student_id": user.student_id,
            "created_at": question.created_at,
        }}, status=status.HTTP_201_CREATED)


    #질문 삭제
    def destroy(self, request, *args, **kwargs):
        student_id = request.data.get('student_id')  # 프론트엔드에서 전송한 student_id

        try:
            # student_id를 사용하여 User 객체 찾기
            user = User.objects.get(student_id=student_id)
        except User.DoesNotExist: #User 객체 존재하지 않다면?
            return Response({"error": "User not found."}, status=status.HTTP_404_NOT_FOUND)

        try:
            # URL에서 제공된 pk를 사용하여 Question 객체를 찾기
            question = Question.objects.get(pk=kwargs['pk'])
        except Question.DoesNotExist:
            return Response({"error": "Question not found."}, status=status.HTTP_404_NOT_FOUND)


        # User가 Question의 작성자와 일치하는지 확인
        if question.author == user:
            question.delete()  # 조건이 충족되면 질문을 삭제
            return Response({"message": "Question deleted successfully"}, status=status.HTTP_204_NO_CONTENT)
        else:
            # 작성자가 일치하지 않으면 오류 메시지를 반환
            return Response({"error": "You do not have permission to delete this question."},
                            status=status.HTTP_403_FORBIDDEN)


    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        answers = Answer.objects.filter(question=instance)
        serializer = self.get_serializer(instance)
        data = serializer.data
        data['answers'] = AnswerSerializer(answers, many=True).data
        return Response(data)

    def update(self, request, *args, **kwargs):
        # 클라이언트로부터 받은 데이터
        data = request.data

        # 클라이언트에서 제공한 student_id를 사용하여 User 객체를 찾습니다.
        student_id = data.get('student_id')
        try:
            user = User.objects.get(student_id=student_id)
        except User.DoesNotExist:
            return Response({"error": "주어진 학번을 가진 사용자가 존재하지 않습니다."},
                            status=status.HTTP_404_NOT_FOUND)

        # URL에서 제공된 question_id를 사용하여 해당 질문을 찾기
        question_id = kwargs.get('pk')
        try:
            question = Question.objects.get(pk=question_id)
        except Question.DoesNotExist:
            return Response({"error": "질문을 찾을 수 없습니다."},
                            status=status.HTTP_404_NOT_FOUND)

        # 질문 작성자와 현재 사용자가 일치하는지 확인
        if question.author == user:
            # 권한이 있는 경우 질문 내용 업데이트
            question.title = data.get('title')
            question.content = data.get('content')
            question.modified_at = timezone.now()  # modified_at 필드 업데이트
            question.save()
            return Response({"message": "질문이 성공적으로 수정되었습니다."}, status=status.HTTP_200_OK)
        else:
            # 작성자가 일치하지 않으면 오류 메시지를 반환
            return Response({"error": "이 질문을 수정할 권한이 없습니다."},
                            status=status.HTTP_403_FORBIDDEN)
728x90
반응형