本文介绍了只允许帖子的作者在基于类的视图中进行编辑-Django?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

views.py

class EditPost(UserPassesTestMixin, LoginRequiredMixin, UpdateView):
    model = Posts
    form_class = PostForm
    template_name="posts/add_post.html"

    def test_func(self):
        x = self.request.user.pk
        print (x)
        y = Posts.objects.get(user='user')
        print (y)
        if x == y:
            return True
        else:
            if self.request.user.is_authenticated():
                raise Http404("You are not allowed to edit this Post")

models.py

models.py

class Posts(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    post = models.CharField(max_length=1200, blank=False)

我如何匹配已登录的用户和帖子的用户对象

由于我使用的是基于类的视图,所以找不到任何解决方案.

i could not find any solution since i am using class based views.

推荐答案

尝试一下:

将分派添加到EditPost类

add dispatch to EditPost class

def dispatch(self, request, *args, **kwargs):
    obj = self.get_object()
    if obj.user != self.request.user:
        raise Http404("You are not allowed to edit this Post")
    return super(EditPost, self).dispatch(request, *args, **kwargs)

这篇关于只允许帖子的作者在基于类的视图中进行编辑-Django?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 12:12