在 Django 基于类的通用视图中访问上下文对象

发布于 2024-11-03 15:33:39 字数 459 浏览 0 评论 0原文

我正在使用 DetailView 来查看 Project 对象,并且我希望能够访问正在查看的 Project 对象,以便将其传递给装饰器,如下所示:

class ProjectDetailView(DetailView):
    context_object_name = "project"
    model = Project

    @method_decorator(membership_required(project))
    def dispatch(self, *args, **kwargs):
        return super(ProjectDetailView, self).dispatch(*args, **kwargs)

但是,传递“project”或“object”装饰器给了我一个“对象”,而不是一个 Project 实例。如何获取该 Project 实例以便我的装饰器函数可以使用它?

I'm using a DetailView to view a Project object, and I would like to be able to access the Project object being viewed in order to pass it to a decorator, something like this:

class ProjectDetailView(DetailView):
    context_object_name = "project"
    model = Project

    @method_decorator(membership_required(project))
    def dispatch(self, *args, **kwargs):
        return super(ProjectDetailView, self).dispatch(*args, **kwargs)

However, passing in "project" or "object" to the decorator gives me an "object", not a Project instance. How can I get that Project instance so my decorator function can work with it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

善良天后 2024-11-10 15:33:39

对象是在dispatch()方法内检索的,因此您的装饰器无法使用它。
您可以检查重写 get() 方法内部的成员资格:

class ProjectDetailView(DetailView):
    context_object_name = "project"
    model = Project

    def get(self, request, **kwargs):
        self.object = self.get_object()
        if not self.object.is_member(self.request.user):
            return HttpResponseRedirect('/') # or something else
        context = self.get_context_data(object=self.object)
        return self.render_to_response(context)

如果您想坚持使用装饰器,则必须根据要查看的参数(id 或 slug)从装饰器内的数据库中检索对象。但是您将从数据库中检索对象两次,第一次是在装饰器中,然后是在视图中。

Object is retrieved inside a dispatch() method, so your decorator can not use it.
You may check membership inside of an overriden get() method:

class ProjectDetailView(DetailView):
    context_object_name = "project"
    model = Project

    def get(self, request, **kwargs):
        self.object = self.get_object()
        if not self.object.is_member(self.request.user):
            return HttpResponseRedirect('/') # or something else
        context = self.get_context_data(object=self.object)
        return self.render_to_response(context)

If you want to stick to decorator, you'll have to retrive object from database within your decorator, based on args (id or slug) to view. But you will be retrieving object from database twice, first in your decorator, and then within a view.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文