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

Getting id of instance in form and save in it

我正在构建一个博客应用程序,我正在开发一个功能,其中 A user can report comment 所以我创建了另一个模型来存储 reports 所以我保存了报告的评论但是我放置了报告表格在详细视图中,因此报告表格将在 post 详细页面的评论下方,其中我在报告时没有得到 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 %}

我尝试了什么:-

comments = post.comment_set.all()

    for com in comments:
        if request.method == 'POST':
            ......
            if reportform.is_valid():
            ....
            ......
            ......
            form.reported_by = com

但它总是保存第一个评论id。

comment_ID = request.POST['comment_id']

但是显示MultiValueDictKeyError错误。

我试了很多次,但是评论的id没有保存在报表实例中。

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

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

另一种方法是创建一个 URL,您可以在其中报告评论:

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

然后您可以将表单提交到该视图:

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