[英]Django How do I edit a comment
how do I edit an existing comment, when a user comment on a post that user can be able to edit his/her 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.....
You have to pass comment id in the updating function like:您必须在更新功能中传递评论 ID,例如:
path('comment/<int:comment_id>/update' ...
and do the following并执行以下操作
CommentForm(instance=Comment.objects.get(id=comment_id), data=request.POST)
UPDATE: to make the same view handles both create and update add new URL that point to same view (and place it under the original one):更新:要使相同的视图处理创建和更新,请添加指向同一视图的新 URL(并将其放在原始视图下):
path('comment/<int:id>/<int:comment_id>/', name='comment_update')
and update your view like this:并像这样更新您的视图:
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.
and in your template: if this form is for update: use <form method="POST" action="{% url 'comment_update' post.id comment.id %}">
并在您的模板中:如果此表单用于更新:使用
<form method="POST" action="{% url 'comment_update' post.id comment.id %}">
if it's create form just use: <form method="POST" action="{% url 'comment_create' post.id %}">
如果是创建表单,只需使用:
<form method="POST" action="{% url 'comment_create' post.id %}">
Can you provide a screenshot of your page?你能提供你的页面截图吗?
post = get_object_or_404(Image)
why you pass image?为什么你通过图像? it should be your ID that are from I guess your post request.
应该是您的 ID 来自我猜您的帖子请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.