对现有数据进行修改Update
class PostUpdate(View):
# why:为什么这样能实现博客的修改而非新增?
form_class = PostForm
model = Post
template_name = 'blog/post_form_update.html'
def get(self, request, year, month, slug):
post = get_object_or_404(self.model,
pub_date__year=year, pub_date__month=month, slug=slug)
return render(request,
self.template_name,
{'form': self.form_class(instance=post), 'post': post})
def post(self, request, year, month, slug):
post = get_object_or_404(self.model,
pub_date__year=year, pub_date__month=month, slug=slug)
# 这里的instance=post是实现博客的修改而非新增的关键
bound_form = self.form_class(request.POST, instance=post)
if bound_form.is_valid():
new_post = bound_form.save()
return redirect(new_post)
else:
return render(request,
self.template_name,
{'form': bound_form, 'post': post})