본문 바로가기

내일배움 캠프/TIL

2023 04 13 django 코멘트 CRUD

오늘은 끄느 스승님이 저에게 코멘트CRUD 구현을 지시하셨습니다

 

저는 그 지시를 듣고 지난번 myspartasns에서 3주차 숙제로 나왔던 코멘트 작성 및 삭제가 기억났었는데

그때는 거의 1시간 이상 걸렸던 숙제였었는데 지금 할때는 그때랑 얼마나 다른지 궁금해서 그때의 기억을 최대한 살려서

구현을 했었습니다

 

먼저 코멘트 작성은

@login_required
def comment_create(request,id):
    post = Post.objects.get(id=id)
    if request.method == 'POST':
        comment = request.POST.get('comment', '')
        if comment == '':
            return redirect('post', post.id)
        else:
            Comment.objects.create(name= request.user.username, 
                comment=comment, user=request.user, post=post)
            return redirect('post', post.id)

해당 코드를 통해 models의 Comment를 불러와서 db에 저장하는 역할을 수행했고

 

삭제 버튼을 눌렀을때는

@login_required
def comment_delete(request, comment_id, id):
    comment = Comment.objects.get(id=comment_id)
    if request.user.id == comment.user_id:
        comment.delete()
    return redirect('post', comment.post.id)

Comment.objects.get을 통해 삭제해야하는 값을가져온다음에 그 값을 삭제하는 역할을 수행하게 했습니다

 

그리고 게시글에 작성한 덧글을 보여주게 하기위해서 게시글이 나타나는 페이지에

comments = Comment.objects.filter(post=post)

Comment.objects.filter을 통해서 게시물의 comment값을 가져온다음에 그 값을 render 에 같이 보내서 덧글이 보여지는 것을 구현했습니다

 

또 덧글의 수정은

@login_required
def comment_edit(request, id, comment_id):
    post = Post.objects.get(id=id)
    comment = Comment.objects.get(id=comment_id)
    if request.method == "POST":
        comment_data = request.POST.get('comment', '')
        if comment == '':
            return redirect('post', post.id)
        else:
            comment.comment = comment_data
            comment.save()
    return redirect('post', post.id)

user_id와 comment_id를 통해서 내가 그 덧글을 작성한 유저인지 확인을 하고 그 덧글을 가져와서 그 값에 수정된 데이터를 넣어서 다시 저장하는방법으로 구현했습니다

'내일배움 캠프 > TIL' 카테고리의 다른 글

jwt simple 사용해보기  (0) 2023.04.21
python 메서드 복습  (0) 2023.04.17
2023 04 12 python thread,process  (0) 2023.04.13
2023 04 11 django 이미지 저장 및 불러오기  (0) 2023.04.11
2023 04 10 git branch 활용법  (1) 2023.04.10