[英]Django How do I edit a comment
如何編輯現有評論,當用戶對帖子發表評論時,該用戶可以編輯他/她的評論。
class Comments(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
commented_image = models.ForeignKey(Image,....)
comment_post = models.TextField()
.......
#urls
path('comments/<id>/', comments, name='comments'),
path('comments/<int:id>/<int:comment_id>, comments, name=' comments')
def comments(request, id, comment_id=None):
post = get_object_or_404(Image, id=id)
if request.method == 'POST':
if comment_id:
edit_form = CommentForm(#codes here)
else:
edit_form = CommentForm(data=request.POST)
form = CommentForm(request.POST)
if form.is_form():
comment = form.save(commit=False)
comment.user = request.user
comment.commented_image = post
comment.save()
return redirect.....
您必須在更新功能中傳遞評論 ID,例如:
path('comment/<int:comment_id>/update' ...
並執行以下操作
CommentForm(instance=Comment.objects.get(id=comment_id), data=request.POST)
更新:要使相同的視圖處理創建和更新,請添加指向同一視圖的新 URL(並將其放在原始視圖下):
path('comment/<int:id>/<int:comment_id>/', name='comment_update')
並像這樣更新您的視圖:
def comments(request, id, comment_id=None):
post = get_object_or_404(Image, id=id)
if request.method == 'POST':
if comment_id:
form = CommentForm(instance=Comment.objects.get(id=comment_id), data=request.POST)
else:
form = CommentForm(data=request.POST)
# Rest of your code.
並在您的模板中:如果此表單用於更新:使用<form method="POST" action="{% url 'comment_update' post.id comment.id %}">
如果是創建表單,只需使用: <form method="POST" action="{% url 'comment_create' post.id %}">
你能提供你的頁面截圖嗎?
post = get_object_or_404(Image)
為什么你通過圖像? 應該是您的 ID 來自我猜您的帖子請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.