我的想法是创建文章和评论的模型。用户启动评论时,他们可以直接创建数据,但是在实际操作中添加评论不会响应。
#views.py
def details(request, article_id):
detail = LifeArticle.objects.get(id=article_id)
comment = LifeComment.objects.get(article=detail)
return render(request, 'lifedetail.html', locals())
def addcomment(request, article_id):
article = LifeArticle.objects.get(id=article_id)
if request.method == "POST":
content = request.POST['content']
r = LifeComment.create(article=article, user=request.user, content=content)
msg = '添加成功'
return render(request, 'lifedetail.html', locals())
else:
return render(request, 'lifedetail.html',)
#urls.py
urlpatterns = [
url(r'^life/(?P<article_id>\d+)/', views.details),
url(r'^article/life/(?P<article_id>\d+)/addcoment/', views.addcomment)
]
#lifedetail.html
{% if detail %}
<div id='article'>
<form action="/article/life/{{detail.id}}/addcoment/" method="POST">
{% csrf_token %}
<tr>
<td>{{ detail.title }}</td>
<td>{{ detail.content }}</td>
<td>{{ detail.user }}</td>
</tr>
</div>
<div id="comment">
{% if comment %}
<tr>
<td>{{ comment.content }}</td>
<td>{{ comment.user }}</td>
</tr>
</div>
{% else %}
<p>暂无评论</p>
{% endif %}
<input type="text" name="content">
<input type="submit" value="提交">
</form>
{% else %}
<p>暂无文章</p>
{% endif %}
{{msg}}
</div>
这些是我的代码。现在我找不到原因了。我也在看Django2.2的文档来发现问题
答案 0 :(得分:1)
我认为问题出在这一行:
r = LifeComment.create(article=article, user=request.user, content=content)
我认为您应该在此处使用objects
r = LifeComment.objects.create(article=article, user=request.user, content=content)
此外,您需要从上下文发送detail
信息:
def addcomment(request, article_id):
article = LifeArticle.objects.get(id=article_id)
if request.method == "POST":
# rest of the code
else:
return render(request, 'lifedetail.html', context={'detail':article})