new to the Django framework and a little rusty with coding. I am currently trying to build a tech blog from the ground up and have been using Django Central tutorials as a guide. Currently, I am stuck on this tutorial, particularly getting my views to show both the details of the post and the comments form.
In the tutorial, the author switches from a class-based view to a function that uses get_object_or_404()
in order to retrieve the post. I was able to switch over to this function without any error messages, yet the post detail returns blank. Returning to a class-based view solves this issue, but I would like to go with the function provided in the tutorial.
Here is the code:
views.py
def post_detail(request, slug):
template_name = 'post_detail.html'
post = get_object_or_404(Post, slug=slug)
comments = post.comments.filter(active=True)
new_comment = None
# Comment posted
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object but don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
return render(request, template_name, {'post': post,
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form})
And here is a screenshot of what a post detail looks like with this function in use: