在 Django 基于类的通用视图中访问上下文对象
我正在使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对象是在dispatch()方法内检索的,因此您的装饰器无法使用它。
您可以检查重写 get() 方法内部的成员资格:
如果您想坚持使用装饰器,则必须根据要查看的参数(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:
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.