Django我如何编辑评论

时间:2020-04-02 19:46:40

标签: python django

当用户对帖子发表评论时,我可以如何编辑现有评论。

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..... 

2 个答案:

答案 0 :(得分:3)

您必须在更新功能中传递评论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 %}">

答案 1 :(得分:0)

您可以提供页面的屏幕截图吗?

post = get_object_or_404(Image)

为什么要传递图片?我应该是您的发帖请求,应该是您的ID。

相关问题