Assignment #1 | Westagram [Mission 8] 댓글 등록 기능 구현

Jayson Hwang·2022년 5월 21일
0

Westagram Project

목록 보기
9/11
post-thumbnail

1.. Postings app 활용

  • 게시물을 저장해서 관리하는 테이블, 댓글을 정리해서 관리하는 테이블은 분리되어 있을 수도 있음
  • 바라보는 관점에 따라 같은 앱에서 관리할 수도, 따로 분리하여 관리할 수도 있음.
  • 이번 프로젝트에서는 모두 같은 앱(postings)에서 관리

2.. models.py

from django.db    import models
from users.models import User

class TimeStampModel(models.Model): 
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)
    
    class Meta: 
        abstract = True

class Comment(TimeStampModel): 
    user    = models.ForeignKey('users.User', on_delete=models.CASCADE)
    post    = models.ForeignKey('Post', on_delete=models.CASCADE)
    comment = models.TextField(max_length=300)

    class Meta: 
        db_table = 'comments'

3.. views.py

📌 내가 작성한 Comment View 코드

class CommentView(View):
    @signin_decorator
    def post(self, request, post_id):	### *args 값 지정
        try: 
            data = json.loads(request.body)
            user = request.user

            post = Post.objects.get(id = post_id)

            Comment.objects.create(
                comment = data['comment'],
                user    = user,
                post    = post,
            )
            return JsonResponse({'message' : 'SUCCESS'}, status = 200)


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

    @signin_decorator
    def get(self, request, post_id):

        comment_list = [{
            'id'        : User.objects.get(id= comment.user.id).id,
            'email'     : User.objects.get(id= comment.user.id).email,
            'username'  : User.objects.get(id= comment.user.id).name,
            'comment'   : comment.comment,
            'created_at': comment.created_at,
            } for comment in Comment.objects.filter(post_id = post_id)
        ]

        return JsonResponse({'RESULT' : comment_list}, status=200)

4..URLconf

postings/urls.py

from django.urls import path
from postings.views import PostView, CommentView

urlpatterns = [
    path('/post', PostView.as_view()),
    path('/comment/<int:post_id>', CommentView.as_view())
]

profile
"Your goals, Minus your doubts, Equal your reality"

0개의 댓글