作为论坛应用程序的问题页面的一部分,每个页面包含多个帖子,其中一个是问题。每个帖子可能有很多评论。但是,由于每页有很多帖子,我不知道如何将每个评论分配给的帖子传递到数据库。
我正在考虑使用HiddenInput,但不确定如何实现它。
代码如下:question_page.html
<tr id="post-comment-row">
<!-- Post a comment -->
{% if user.is_authenticated %}
<tr>
<form id="comment_form" method="post" action="."
enctype="multipart/form-data">
{% csrf_token %}
<!-- Display form -->
{{ comment_form.as_p }}
<!-- Provide a button to click to submit the form -->
<input type="submit" name="submit" value="Post">
</form>
</tr>
{% else %}
Please login to post a comment
{% endif %}
</tr>
views.py:
# Show each individual question
def show_question_page(request, module_name_slug, question_page_name_slug, post_context=None):
context_dict = {}
module = Module.objects.get(slug=module_name_slug)
question_page = QuestionPage.objects.get(slug=question_page_name_slug)
question_posts = QuestionPost.objects.filter(page=question_page)
comments = Comment.objects.filter(post__in=question_posts)
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Save user data to database
# Save comment instance
comment = comment_form.save(commit=False)
comment.post = post_context
comment.user_profile = UserProfile.objects.filter(user=request.user)
comment.save()
else:
# Invalid form(s): Print errors to console/log
print(comment_form.errors)
else:
comment_form = CommentForm
context_dict['question_posts'] = question_posts
context_dict['question_page'] = question_page
context_dict['comments'] = comments
context_dict['module'] = module
context_dict['comment_form'] = comment_form
return render(request, 'forum/questionPage.html', context_dict)
您需要创建一个带有命名组的 URL,以便post.id
捕获正在为其创建评论的帖子id
。
url(r'app/post/(?P<post_id>d+)/comment/create', show_question_page, name='create-comment')
您可以在表单的操作 URL 中传递post.id
。
action={% url 'create-comment' post.id %}
在视图中,您可以从请求对象获取传递的post_id
并创建与帖子相关的评论。
comment = comment_form.save(commit=False)
post_id = request.POST.get('post_id')
comment.post = get_object_or_404(QuestionPost, id=post_id)
comment.user_profile = UserProfile.objects.filter(user=request.user)