1👍
✅
You can not return aq ValidationError
in the view, you need to return a HTTP response, or raise a Http404
exception for example:
from django.http import Http404
from django.shortcuts import redirect
def ListViewPage(request):
queryset = Post.objects.all()
if request.method == 'POST':
try:
pk = request.POST.get('pk')
post = Post.objects.get(id=pk)
except Post.DoesNotExist:
raise Http404(f'No Post by id {pk}')
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
comment_form.instance.posts = post
comment_form.save()
return redirect('name-of-some-view')
else:
comment_form = CommentForm()
context = {
'posts': queryset,
'form': comment_form
}
return render(request, 'post_list.html', context)
Note: In case of a successful POST request, you should make a
redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.
Source:stackexchange.com