【问题标题】:Django Improved UpdateView?Django 改进了更新视图?
【发布时间】:2019-12-16 21:28:03
【问题描述】:

我有这个 UpDateView 类,我只需要文章的作者就可以编辑博客。我有 CreateView 类的解决方案(使用 def Form_valid),但它不适用于 UpdateView 类 :::

class ArticleUpdateView(LoginRequiredMixin,UpdateView):
    model = models.Article
    template_name = 'article_edit.html'
    fields = ['title','body']
    login_url = 'login'

class ArticleCreateView(LoginRequiredMixin,CreateView):
    model = models.Article
    template_name = 'article_new.html'
    fields = ['title','body',]
    login_url='login'


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

【问题讨论】:

  • 为什么不呢?将 form_valid 添加到更新类时会发生什么?
  • 实际上它让我感到惊讶,因为从逻辑上它应该可以工作。我创建了 3 个用户,但每个用户都可以编辑和删除其他用户的帖子。我为其他视图复制并粘贴了 Form_valid,但它只适用于 CreateView....

标签: django django-views


【解决方案1】:

您可以在视图类中覆盖get_object 方法:

class ArticleUpdateView(LoginRequiredMixin,UpdateView):
    model = models.Article
    template_name = 'article_edit.html'
    fields = ['title','body']
    login_url = 'login'

    def get_object(self, *args, **kwargs):
        article = super().get_object(*args, **kwargs)

        if article.author != self.request.user:
            raise PermissionDenied('You should be the author of this article.')

        return article

【讨论】:

  • 成功了,非常感谢伙计。 ??。我需要深入研究您的解决方案,再次感谢
  • @DaniMHM 我很高兴能帮上忙。请务必接受该解决方案,以指导您的问题的未来查看者。
猜你喜欢
  • 1970-01-01
  • 2016-08-29
  • 1970-01-01
  • 2022-10-07
  • 1970-01-01
  • 2020-10-20
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
相关资源
最近更新 更多