【发布时间】:2023-03-13 05:29:01
【问题描述】:
我无法将特定 cmets 指向我的 Django 网站中的特定对象。在下面的 HTML 页面上,显示了 5 个posts 及其各自的属性。每个post 都有自己的comment_form,用户可以在其中留下cmets。然而,当留下评论时,所有帖子都共享相同的 cmets,而不是他们自己独特的 cmets 集。有没有人推荐我给每个post 提供他们自己独特的comments 集合,这样他们就不会共享同一个?
这是我当前的 HTML:
<div class="mainContent">
<div class="content">
{% for post in posts %}
<article class="topContent">
<div>
<h1>{{ post.title }}</h1>
<p>{{ post.body }}</p>
<h6><i>published {{ post.pub_date }}</i></h6>
<div class="commentForm">
{% for comment in comments %}
<p id="commentP">{{ comment.comment }} - {{ comment.name }}</p>
{% endfor %}
</div>
<form method="POST" action="">
{% csrf_token %}
<div id='comment_form'>
<div id="namePrompt">
<p> Name:</p>
</div>
<div id="formName">
{{form.name}}
</div>
<div id="commentPrompt">
<p> Comment: </p>
<div id="formComment">
{{form.comment}}
</div>
<div id="submitBtn">
<input type='submit' name='submit' value='Add Comment'>
</div>
</div>
</form>
</div>
</article>
{% endfor %}
</div>
</div>
这里是视图:
def projects(request):
print request
posts = ProjectsPost.objects.all()
comment_from_db = ProjectComment.objects.all()
form = ProjectCommentForm(request.POST or None)
if form.is_valid():
new_form = form.save(commit=False)
name = form.cleaned_data['name']
comment = form.cleaned_data['comment']
context_comment = ProjectComment.objects.get_or_create(name=name, comment=comment)
print context_comment
template = "blog/projects.html"
context = {"form":form}
project_posts = {'posts':posts}
return render(request, template, {'form':form, 'posts':posts, 'comments':comment_from_db})`
【问题讨论】:
-
我能不能创建一个 Comment() 模型并使用 ForeignKey 将其绑定到 ProjectPost() 的主键 (pk),然后使用 Comment() 作为 ProjectCommentForm() 的 Meta 类,以及通过我的views.py渲染它?或者如果这不起作用,是否有更有效的方法?