프로젝트 라이언_백엔드05 : CRUD

Bnow·2022년 8월 21일

CRUD

1) 설명

  1. Create : 게시글 생성
  2. Read : 게시글 상세보기, 해당 유저만
  3. Update : 게시글 수정
  4. Delete : 게시글 삭제

2) 방식

    url - view - template(html) 순으로 수정

3) 코드

urls.py

urlpatterns = [
    path('', post_list_view, name='post-list'),
    path('create/', post_create_view, name='post-create'),
    path('<int:id>/', post_detail_view, name='post-detail'),
    path('<int:id>/edit/', post_update_view, name='post-update'),
    path('<int:id>/delete/', post_delete_view, name='post-delete')
]

views.py

def post_create_view(request):
    if request.method =='GET': #페이지 불러올때
        return render(request, 'posts/post_form.html')
    else:
        image = request.FILES.get('image')
        content = request.POST.get('content')
        print(image)
        print(content)
        Post.objects.create(
            image=image,
            content=content,
            writer = request.user
        )
        return redirect('index')

def post_detail_view(request, id):
    try:
        post=Post.objects.get(id =id)
    except Post.DoesNotExist:
        return redirect('index')
    context={
        'post':post,
    }
    return render(request, 'posts/post_detail.html', context) 

def post_update_view(request, id):
    #post = Post.objects.get(id=id)
    post = get_object_or_404(Post, id=id)
    if request.method =='GET':
        context = {'post' : post}
        return render(request, 'posts/post_form.html', context)
    elif request.method =='POST':
        new_image = request.FILES.get('image')
        content = request.POST.get('content')

        if new_image:
            post.image.delete()     #기존 이미지 삭제
            post.image = new_image  #새 이미지 추가

        post.content = content
        post.save()

        return redirect('posts:post-detail', post.id)

def post_delete_view(request, id):
    post = get_object_or_404(Post, id=id)

    # if request.user != post.writer:
    #     return Http404('잘못된 접근입니다.')

    if request.method == 'GET':
        context = {'post': post}
        return render(request, 'posts/post_conform_delete.html', context)
    else:
        post.delete()
        return redirect('index')

html

  1. create - post_form.html
  2. read - post_detail.html
  3. update - post_form.html, post_detail.html
  4. delete - post_conform_delete.html
profile
행복한 코딩

0개의 댓글