Django Assignment 1 | Westagram 7)

김기현·2022년 2월 24일
0
post-thumbnail

[Mission 8] 게시물 댓글 등록 기능 구현

미션

  • Postings app 활용
    django에서는 다루는 데이터를 기준으로 앱을 분리하여 관리합니다.
    하지만 postings앱에서 posting, comment 두 데이터 모두 관리합니다.
  • Comment Model 생성
    댓글을 등록하기 위해서는 댓글이 달린 게시물, 댓글을 다는 사용자, 생성 시간, 댓글의 내용이 포함되어야 합니다.
    Foreign Key를 이용하여 댓글, 유저, 그리고 게시물 사이의 관계를 만들어 주세요.
  • Comment View 생성 - 댓글 등록
    CommentView 클래스를 생성합니다.
    댓글을 등록할 때에는 post메소드를 사용하며 댓글을 생성한 시간은 현재 시간이어야 합니다.
  • Comment View 생성 - 댓글 표출
    댓글을 나타낼 때에는 get메소드를 사용합니다.
  • Urls.py 작성
    클라이언트의 요청을 받아서 댓글 뷰를 호출할 수 있도록 urls.py 를 작성해 주세요.

수정 사항들 내용

  • 모델링
 # postings/models
class Comment(TimeStampedModel):
    comment = models.CharField(max_length=300)
    user    = models.ForeignKey('users.User', related_name='comments', on_delete=models.PROTECT) 
    post    = models.ForeignKey('Post', related_name='comments', on_delete=models.CASCADE)

    class Meta:
        db_table = "comments" 
  • url 연결
# postings/urls
from django.urls import path
from .views import PostingView, CommentView

urlpatterns = [
    path("upload", PostingView.as_view()),
    path("comment", CommentView.as_view()),
] 
  • post
import json, jwt
from django.views import View
from django.http  import JsonResponse

from users.models     import User
from .models          import Post, Comment
from secret           import ALGORITHM
from config.settings  import SECRET_KEY


class CommentView(View):
    def post(self, request):
        try:
        	data    = json.loads(request.body)
            comment = data['comment']
            post_id = data['post_id']
            payload = jwt.decode(data["token"], SECRET_KEY, ALGORITHM)
            user_id = payload['user_id']


            if not User.objects.filter(id = user_id).exists():
                return JsonResponse({'MESSAGE': "User Does Not Exist"}, status=404)

            if not Post.objects.filter(id = post_id).exists(): 
                return JsonResponse({'MESSAGE': "Posting Does Not Exist"}, status=404)
            
            Comment.objects.create(
                comment = comment,
                user_id = payload['user_id'],
                post_id = post_id,
            )

            return JsonResponse({"MESSAGE": "Post created!"}, status=201)

        except KeyError:
            return JsonResponse({"MESSAGE": "KEY_ERROR"}, status=400)

comment를 하기 위해서는 토큰으로 인증된 유저, 포스트id, comment가 필요합니다.

만약 User db에 있는 id가 유저로부터 입력받은 user_id와 비교해 존재하지 않는다면(다르다면) 유저가 존재하지 않는다는 메시지를 던져줍니다. 그리고 Post의 id와 입력받은 post_id와 비교해 존재하지 않는다면(다르다면) 포스팅이 존재하지 않는다는 메시지를 던져줍니다. 여기서 user = User.objects.all()로 지정해 user.id로 변경할 수 있습니다.

  • get
class CommentView(View):
	.
    .
    .
    def get(self, request):
        comments = Comment.objects.all()
        results = []

        for comment in comments:
            results.append(
                {
                "comment" : comment.comment,
                "post_id" : comment.post_id,
                "user_id" : comment.user_id,
                "post" : {
                    "post_title" : comment.post.post_title,
                    "post_content" : comment.post.post_content,
                    }   
                }
            )
        return JsonResponse({"postings" : results}, status = 200)

Comment의 항목들을 comments에 저장 후 for문을 돌려 하나씩 정보들을 저장합니다.

user_id와 user.id간의 관계

  • view

  • 결과(with postman)

profile
피자, 코드, 커피를 사랑하는 피코커

0개의 댓글