简体   繁体   中英

Display comment content on delete page

I'm not able to display content of comment in Django template. do i have to pass something to the view or do i just call the object simply the wrong way.

views.py

def comment_delete(request, pk):
    comment = get_object_or_404(Comment, pk=pk)

    try:
        if request.method == 'POST':
            comment.delete()
            messages.success(request, 'You have successfully deleted the Comment')
            return redirect('post_detail', pk=comment.post.pk)
        else:
            template = 'myproject/comment_delete.html'
            form = CommentForm(instance=comment)
            context = {
                'form': form,
            }
            return render(request, template, context)
    except Exception as e:
        messages.warning(request, 'The comment could not be deleted. Error {}'.format(e))

models.py

class Comment(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    content = models.TextField()
    published_date = models.DateField(auto_now_add=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.content

template.html

 <div class="class-one-box">
        <p>{{ comment.post.content }}</p>
        <p>Are you sure that you want to delete this Comment? If so, please confirm.</p>
        <form method="POST">
            {% csrf_token %}
            <button class="btn btn-danger" type="submit">Delete Comment</button>
        </form>
    </div>

Yes, you need to pass the comment object through context. So try like this:

    if request.method == 'POST':
        comment.delete()
        messages.success(request, 'You have successfully deleted the Comment')
        return redirect('post_detail', pk=comment.post.pk)
    else:
        template = 'myproject/comment_delete.html'
        form = CommentForm(instance=comment)
        context = {
            'comment': comment,  # <-- Here
            'form': form,
        }
        return render(request, template, context)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM