def create_or_edit_post(request, post, template): if request.method == 'GET': form = CreatePostForm(instance=post) context = { 'form': form, 'post': post, } return render(request, f'{template}.html', context) else: old_image = post.image form = CreatePostForm(request.POST, request.FILES, instance=post) if form.is_valid(): if old_image: os.remove(old_image.path) post = form.save(commit=False) post.user = request.user.userprofile post.save() return redirect('post details', post.pk) context = { 'form': form, 'post': post, } return render(request, f'{template}.html', context)
def edit_post(request, pk): post = Post.objects.get(pk=pk) if request.method == 'GET': form = CreatePostForm(instance=post) context = { 'form': form, 'post': post, } return render(request, 'post_edit.html', context) else: old_image = post.image form = CreatePostForm(request.POST, request.FILES, instance=post) if form.is_valid(): if old_image: os.remove(old_image.path) post = form.save(commit=False) post.save() return redirect('post details', post.pk) context = { 'form': form, 'post': post, } return render(request, 'post_details.html', context)