Access to a context object in a general view based on the Django class

I use a DetailView to view the Project object, and I would like to have access to the Project object that is being viewed to pass it to the 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 it to the “project” or “object” to the decorator gives me the “object”, not the project instance. How can I get this instance of the project so that my decorator function can work with it?

+4
source share
1 answer

The object is retrieved inside the dispatch () method, so your decorator cannot use it. You can check membership in the 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 with the decorator, you will need to restore the object from the database in your decorator based on the arguments (id or slug) to view. But you will retrieve the object from the database twice, first in your decorator, and then in the view.

+7
source

All Articles