I have a method that inserts a new Comment into the base, and after doing so, it redirects back to the previous post, which can be any. So, to do that, I made the following rule:
return redirect(reverse('blog:post', args = (post_id,)))
With it, the page is redirected back to the previous Post being read, by passing to the URL the id.
The problem is now in case the form is not valid. I want to display error messages, but I think that the way it is now, the form is being recreated, erasing any message. So, in the else condition, I want to, instead of redirecting, rendering it again and showing the messages. I've done it like this:
return render(request, 'blog/post.html', post_id = post_id)
But then, I need to get back to the same page I was, regardless the id in the parameter. I need to pass the post_id as I did in the redirect function, but I can't find a way.
This is the whole method:
def write_comment(request, post_id):
"""
Write a new comment to a post
"""
form = CommentForm(request.POST or None)
if form.is_valid():
post = Post.objects.get(pk = post_id)
post.n_comments += 1
post.save()
comment = Comment()
comment.comment = request.POST['comment']
comment.created_at = timezone.now()
comment.modified_at = timezone.now()
comment.post_id = post_id
comment.user_id = 2
comment.save()
return redirect(reverse('blog:post', args = (post_id,)))
else:
# Need to pass the parameter here, in order to not recreate the form
return render(request, 'blog/post.html')
My class view used to display the Post, depending on its id, by the URL:
url(r'^post/(?P<id>[0-9]+)/$', views.GetPostView.as_view(), name = 'post'),
And the GetPostView:
class GetPostView(TemplateView):
"""
Render the view for a specific post and lists its comments
"""
template_name = 'blog/post.html'
def get(self, request, id):
return render(request, self.template_name, {
'post': Post.objects.get(pk = id),
'comments': Comment.objects.filter(post = id).order_by('-created_at'),
'form': CommentForm()
})