在表单中获取实例id并保存在其中



我正在构建一个博客应用程序,我正在研究一个功能,其中A user can report comment,所以我创建了另一个模型来存储reports,所以我保存了哪个评论被报告,但是我将报表放在详细视图中,因此报表将在帖子详细页面的评论下方,其中我在报告时没有得到comment id

models.py

class Blog(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=1000)
class Comment(models.Model):
commented_by = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.CharField(max_length=1000)
class ReportComment(models.Model):
reported_by = models.ForeignKey(User, on_delete=models.CASCADE)
reported_comment = models.ForeignKey(Comment, on_delete=models.CASCADE)
text = models.CharField(max_length=1000)

views.py

def blog_detail_page(request, blog_id):
post = get_object_or_404(Blog, pk=blog_id)
if request.method == 'POST':
reportform = CommentReportForm(data=request.POST)
if FlagCommentForm.is_valid():
form = reportform.save(commit=False)
# Saving in this line
flagForm.reported_comment = reportform.id
form.reported_by = request.user
form.save()
return redirect('home')
else:
reportform = CommentReportForm()


context = {'reportform':reportform, 'post':post}
return render(request, 'blog_detail_page.html', context)

blog_detail_page.html


{{post.title}}

{% for comment in post.comment_set.all %}
{{comment.body}}

<div class="container">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<table>
{{ reportform }}
</table>
<button type="submit">Save</button>
</form>
</div>
{% endfor %}

What have I try:-

  • 我也尝试过使用循环:-
comments = post.comment_set.all()
for com in comments:
if request.method == 'POST':
......
if reportform.is_valid():
....
......
......
form.reported_by = com

但是它总是保存第一个注释id。

  • 然后我尝试了request.POST方法,如:-
comment_ID = request.POST['comment_id']

但是显示MultiValueDictKeyError错误。

我已经尝试了很多次,但是评论的id没有与报告实例一起保存。

您需要将评论的主键添加到表单中,或者添加到提交表单的URL中。例如作为隐藏表单元素:

<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="hidden" name="comment_id"value="{{ comment.pk }}">
<table>
{{ reportform }}
</table>
<button type="submit">Save</button>
</form>

另一种方法是创建一个URL,在其中报告注释:

urlpatterns = [
path('comment/<int:comment_id>/report', some_view, name='report-comment')
]

,然后你可以用:

<form method="post"action="{% url 'report-comment' comment_id=comment.pk %}"enctype="multipart/form-data">
{% csrf_token %}
<table>
{{ reportform }}
</table>
<button type="submit">Save</button>
</form>

相关内容

  • 没有找到相关文章

最新更新