如何在Django中更新和删除评论

How to update and delete comments in Django

我正在努力更新和删除用户创建的评论,我已经为评论创建了 Class 基于视图,但我不确定如何继续,因为我遇到了错误

是否有任何其他选项可供用户删除和编辑他们的评论?

我目前收到的错误是:

FieldError at /blog/sdsdssds/update_comment/
Cannot resolve keyword 'slug' into field. Choices are: content, created, id, post, post_id, updated, user, user_id

关于如何修复此错误的任何想法及其原因是什么?

这里是models.py

class Post(models.Model):
    title = models.CharField(max_length=100, unique=True)
    content = RichTextUploadingField(null=True, blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author')
    date_posted = models.DateTimeField(default=timezone.now)
    slug = models.SlugField(blank=True, null=True, max_length=120)
    liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked')

class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    content = models.TextField(max_length=300, validators=[validate_comment_text])

这是views.py

class PostCommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    form_class = CommentForm

    def form_valid(self, form):
        post = get_object_or_404(Post, slug=self.kwargs['slug'])
        form.instance.user = self.request.user
        form.instance.post = post
        return super().form_valid(form)

    def form_invalid(self, form):
        return HttpResponseRedirect(self.get_success_url())

    def get_success_url(self):
        return reverse('blog:post-detail', kwargs=dict(slug=self.kwargs['slug']))

class PostCommentUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Comment
    fields = ['content']  # What needs to appear in the page for update
    template_name = 'blog/post_detail.html'  # <app>/<model>_<viewtype>.html

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

    def form_invalid(self, form):
        return HttpResponseRedirect(self.get_success_url())

    def get_success_url(self):
        return reverse('blog:post-detail', kwargs=dict(slug=self.kwargs['slug']))

    def test_func(self):
        comment = self.get_object()
        if self.request.user == comment.user:
            return True
        return False

class PostCommentDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = Comment
    template_name = 'blog/postcomment_confirm_delete.html'  # <app>/<model>_<viewtype>.html

    def test_func(self):
        comment = self.get_object()
        if self.request.user == comment.user:
            return True
        return False

    def form_invalid(self, form):
        return HttpResponseRedirect(self.get_success_url())

    def get_success_url(self):
        return reverse('blog:post-detail', kwargs=dict(slug=self.kwargs['slug']))

这是模板:

            {% for comment in comments %}
                <ul class="list-unstyled">
                  <li class="media">
                    <img class="rounded-circle article-img" src="{{ comment.post.author.profile.image.url }}">
                      <div class="media-body">
                      <h5 class="mt-0 mb-1">{{comment.user| capfirst}}<small class="text-muted">- {{ comment.created}}</small> </h5>
                        <hr class="solid mt-0">
                        {{ comment.content}}
                      </div>
                  </li>
                </ul>
               {% if comment.user == user %}
                  <div>
                    <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'blog:post-commentu' post.slug %}">Update</a>
                    <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'blog:post-commentd' post.slug %}">Delete</a>
                  </div>
                {% endif %}
            {% endfor %}

这里是urls.py

    path('blog/<slug:slug>/add_comment/',
         PostCommentCreateView.as_view(), name='post-comment'),
    path('blog/<slug:slug>/update_comment/',
         PostCommentUpdateView.as_view(), name='post-commentu'),
    path('blog/<slug:slug>/delete_comment/',
         PostCommentDeleteView.as_view(), name='post-commentd'),

重命名 Post 模型中的 slug 字段,我认为它会导致碰撞。

class Post(models.Model):
    title = models.CharField(max_length=100, unique=True)
    content = RichTextUploadingField(null=True, blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author')
    date_posted = models.DateTimeField(default=timezone.now)
    slug_field = models.SlugField(blank=True, null=True, max_length=120)
    liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked')


虽然您的评论模型没有,但您正在向您的 Url 传递一个鼻涕虫。您需要传递给 url 的是评论的唯一 ID,而不是它所属的 post 的别名。