Во-первых, он вернет ошибку:
Не вернул объект HttpResponse
Поскольку, если ваш form.is_valid()
возвращает False
, выполнение не выполняетсяпуть для продолжения и, таким образом, возвращается None
.
Вам необходимо сделать следующее:
def comment_new(request, pk):
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
post = get_object_or_404(Post, pk=pk)
comment = form.save(commit=False)
comment.author = request.user
comment.published_date = timezone.now()
comment.post = post
comment.save()
return redirect('post_detail', pk=comment.post.pk)
else: # If for is NOT valid:
form = CommentForm(request.POST)
return render(request, 'MyProject/comment_new.html', {'form': form})
else:
form = CommentForm()
return render(request, 'MyProject/comment_new.html', {'form': form})
Или чтобы код не повторялся визуально (сохраняйте «СУХОЙ»):
def comment_new(request, pk):
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
post = get_object_or_404(Post, pk=pk)
comment = form.save(commit=False)
comment.author = request.user
comment.published_date = timezone.now()
comment.post = post
comment.save()
return redirect('post_detail', pk=comment.post.pk)
else:
form = CommentForm()
# Note the indentation (this code will be executed both if NOT POST
# and if form is not valid.
return render(request, 'MyProject/comment_new.html', {'form': form})