我正在構建一個博客應用程式,我正在開發一個功能,A user can report comment因此我創建了另一個用于存盤的模型,reports 因此我正在保存報告的評論但是我將報告表單放在詳細視圖中,因此報告表單將在帖子詳細資訊頁面的評論下方,其中我沒有得到comment id報告時。
模型.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)
視圖.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。
- 然后我通過
request.POST方法嘗試,例如:-
comment_ID = request.POST['comment_id']
但是顯示MultiValueDictKeyError錯誤。
我已經嘗試了很多次但是評論的 id 沒有與報告實體一起保存。
任何幫助將非常感激。謝謝
uj5u.com熱心網友回復:
您需要將評論的主鍵添加到表單或提交表單的 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/334402.html
標籤:Python 姜戈 django-models django-views django-queryset
