1. Monwara LLC
  2. Untitled project
  3. django-related

Commits

Branko Vukelic  committed 0269729

Grab the related object in dispatch method

  • Participants
  • Parent commits 4214d56
  • Branches master

Comments (0)

Files changed (2)

File related/views.py

View file
     related_object_name = None
     cache_backend = cache
 
+    def dispatch(self, request, *args, **kwargs):
+        self.related_object = self.get_related_object()
+        return super(RelatedObjectMixin, self).dispatch(
+            request, *args, **kwargs
+        )
+
     def get_related_404_url(self):
         return self.related_404_redirect_url
 
     def get_context_data(self, *args, **kwargs):
         context = super(RelatedObjectMixin, self).get_context_data(*args, **kwargs)
 
-        related_object = self.get_related_object()
-
-        context['related_object'] = related_object
+        context['related_object'] = self.related_object
 
         related_object_name = self.get_related_object_name()
         if related_object_name:
-            context[related_object_name] = related_object
+            context[related_object_name] = self.related_object
 
         return context
 

File tests/tests.py

View file
 
     def test_context(self):
         class Super(object):
+            def dispatch(self, request, *args, **kwargs):
+                return
+
             def get_context_data(self):
                 return dict()
 
 
         view = View()
         view.get_related_object = Mock()
+        view.dispatch(Mock())  # Fake dispatch call with a mock object
 
         ctx = view.get_context_data()
         view.get_related_object.assert_called_once()
 
     def test_related_object_name(self):
         class Super(object):
+            def dispatch(self, request, *args, **kwargs):
+                return
+
             def get_context_data(self):
                 return dict()
 
 
         view = View()
         view.get_related_object = Mock()
+        view.dispatch(Mock())  # Fake dispatch call with mock object
         view.related_object_name = 'foo_object'
 
         ctx = view.get_context_data()