瀏覽代碼

Refs #20456 -- Moved initialization of HEAD method based on GET to the View.setup() for generic views.

This will ease unit testing of views since setup will essentially do
everything needed to set the view instance up (other than instantiating
it). Credit for idea goes to Vincent Prouillet.
Felipe Lee 5 年之前
父節點
當前提交
c2c27867ef
共有 4 個文件被更改,包括 12 次插入7 次删除
  1. 1 0
      AUTHORS
  2. 2 2
      django/views/generic/base.py
  3. 2 5
      docs/ref/class-based-views/base.txt
  4. 7 0
      tests/generic_views/test_base.py

+ 1 - 0
AUTHORS

@@ -286,6 +286,7 @@ answer newbie questions, and generally made Django that much better:
     favo@exoweb.net
     fdr <drfarina@gmail.com>
     Federico Capoano <nemesis@ninux.org>
+    Felipe Lee <felipe.lee.garcia@gmail.com>
     Filip Noetzel <http://filip.noetzel.co.uk/>
     Filip Wasilewski <filip.wasilewski@gmail.com>
     Finn Gruwier Larsen <finn@gruwier.dk>

+ 2 - 2
django/views/generic/base.py

@@ -60,8 +60,6 @@ class View:
 
         def view(request, *args, **kwargs):
             self = cls(**initkwargs)
-            if hasattr(self, 'get') and not hasattr(self, 'head'):
-                self.head = self.get
             self.setup(request, *args, **kwargs)
             if not hasattr(self, 'request'):
                 raise AttributeError(
@@ -82,6 +80,8 @@ class View:
 
     def setup(self, request, *args, **kwargs):
         """Initialize attributes shared by all view methods."""
+        if hasattr(self, 'get') and not hasattr(self, 'head'):
+            self.head = self.get
         self.request = request
         self.args = args
         self.kwargs = kwargs

+ 2 - 5
docs/ref/class-based-views/base.txt

@@ -79,12 +79,9 @@ MRO is an acronym for Method Resolution Order.
 
     .. method:: setup(request, *args, **kwargs)
 
-        Initializes view instance attributes: ``self.request``, ``self.args``,
-        and ``self.kwargs`` prior to :meth:`dispatch`.
+        Performs key view initialization prior to :meth:`dispatch`.
 
-        Overriding this method allows mixins to setup instance attributes for
-        reuse in child classes. When overriding this method, you must call
-        ``super()``.
+        If overriding this method, you must call ``super()``.
 
     .. method:: dispatch(request, *args, **kwargs)
 

+ 7 - 0
tests/generic_views/test_base.py

@@ -113,6 +113,13 @@ class ViewTest(SimpleTestCase):
         response = SimpleView.as_view()(self.rf.head('/'))
         self.assertEqual(response.status_code, 200)
 
+    def test_setup_get_and_head(self):
+        view_instance = SimpleView()
+        self.assertFalse(hasattr(view_instance, 'head'))
+        view_instance.setup(self.rf.get('/'))
+        self.assertTrue(hasattr(view_instance, 'head'))
+        self.assertEqual(view_instance.head, view_instance.get)
+
     def test_head_no_get(self):
         """
         Test a view which supplies no GET method responds to HEAD with HTTP 405.