user11040244
user11040244

Reputation:

Django - redirect after pressing comment delete

I have a code that deletes comments to from posts.

def comment_remove(request, pk):
    comment = get_object_or_404(Comment, pk=pk)
    comment.delete()

    return redirect('Post-detail', pk=post.pk)

It deletes comments, but it throws error that name 'post' is not defined I have a same function above in my views.py with the same post.pk that works fine...

@login_required
def add_comment_to_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.author = request.user
            #comment.author.photo = object.author.profile.image.url
            comment.save()
            return redirect('Post-detail', pk=post.pk)
    else:
        form = CommentForm()
    return render(request, 'blog/add_comment_to_post.html', {'form': form})

Comment model

class Comment(models.Model):
    post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments')
    author = models.CharField(max_length=20)
    text = models.TextField(max_length=200)
    created_date = models.DateTimeField(default=timezone.now)
    approved_comment = models.BooleanField(default=False)

    def approve(self):
        self.approved_comment = True
        self.save()

    def __str__(self):
        return self.text

Can someone please explain me, where is the problem? Is it taking no post.pk but comment.pk?

Upvotes: 1

Views: 167

Answers (1)

shafikshaon
shafikshaon

Reputation: 6404

You can pick pk from comment object like this

comment = get_object_or_404(Comment, pk=pk)
....
return redirect('Post-detail', pk=comment.post_id)

Upvotes: 1

Related Questions