def comment_edit(request, report_id, comment_id=None): """感想の編集""" report = get_object_or_404(Report, pk=report_id) # 親の書籍を読む if comment_id: # comment_id が指定されている (修正時) comment = get_object_or_404(Comment, pk=comment_id) else: # comment_id が指定されていない (追加時) comment = Comment() if request.method == 'POST': form = CommentForm(request.POST, instance=comment) # POST された request データからフォームを作成 if form.is_valid(): # フォームのバリデーション comment = form.save(commit=False) comment.report = report # この感想の、親の書籍をセット comment.save() return redirect('polls:comment_list', report_id=report_id) else: # GET の時 form = CommentForm(instance=comment) # comment インスタンスからフォームを作成 return render(request, 'polls/comment_edit.html', dict(form=form, report_id=report_id, comment_id=comment_id))