I'm relatively new to python/django and I'm not sure I'm doing this right
Suppose there are 2 different apps projects and items. The url I have in the items app is:
path('projects/<slug:project_slug>/items/', ItemListView.as_view())
And the cb-view:
class ItemListView(CanViewProjectMixin, ListView):
model = Item
def get(self, request, *args, **kwargs):
self.project = Project.objects.get(slug=kwargs.get('project_slug'))
return super(ItemListView, self).get(request, *args, **kwargs)
def get_context_data(self, *, object_list=None, **kwargs):
context = super(ItemListView, self).get_context_data(**kwargs)
context['project'] = self.project
return context
This seems to work fine in the view, and it is passing the project object to the template via context
However, I'm not able to get self.project in the CanViewProjectMixin.dispatch() method.
Any help would be appreciated
Update
CanViewProjectMixin has a get_permission_object() method which retrieves the project object in the main project app views where project is retrieved via default get_object() or via self.project where the view is a child of project like in the example above.
def get_permission_object(self):
if hasattr(self, 'project'):
return self.project
return (hasattr(self, 'get_object') and self.get_object() or
getattr(self, 'object', None))
def dispatch(self, request, *args, **kwargs):
self.object = self.get_permission_object()
...
# do stuff with the object and return super()
On project views where project is retrieved via get_object() it works just fine, the problem is only on child views
getmethod runs afterdispatch. If think you should attachself.projectin dispatch if you need it there too.CanViewProjectMixin?ItemListViewdefinesself.projectin thegetmethod. That's too late if you want to use it indispatch. You need to defineself.projectindispatch(Django < 2.2) orsetupas in my answer (Django >= 2.2).