Django How do I edit a comment

Question:

how do I edit an existing comment, when a user comment on a post that user can be able to edit his/her comment.

models.py

class Comments(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    commented_image = models.ForeignKey(Image, ...) 
    comment_post = models.TextField() 

urls.py

path('comments/<id>/', comments, name='comments'),
path('comments/<int:id>/<int:comment_id>', comments, name='comments')

views.py

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(...) 
Asked By: Oghomwen Oguns

||

Answers:

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.

Answered By: Eyakub

You have to pass comment id in the updating function like:

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):

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 %}">

if it’s create form just use:
<form method="POST" action="{% url 'comment_create' post.id %}">

Answered By: Ashraf Emad
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.