CRUD
1) 설명
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