6

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?

Asterism
  • 63
  • 1
  • 1
  • 3

1 Answers1

9

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.

Ivan Virabyan
  • 1,666
  • 2
  • 19
  • 25
  • Could you tell me why I need to use `self.request.user` instead of only `request.user`? I tried the code with `request.user` and it worked, but I don't know if that is a coincidence. – Asterism May 02 '11 at 05:55
  • 1
    yes, you can use `request.user`, because it is passed as a parameter to the method. I just didn't notice that. Usually when I override methods in class-based views, they don't get request as parameter (methods like `get_context_data`, `get_query_set`, `get_object` and others). – Ivan Virabyan May 03 '11 at 07:27