Code

Ticket #16502: get_model_with_tests.diff

File get_model_with_tests.diff, 6.2 KB (added by Silver_Ghost, 3 years ago)

Separate get_model-patch.

Line 
1diff --git a/django/views/generic/detail.py b/django/views/generic/detail.py
2--- a/django/views/generic/detail.py
3+++ b/django/views/generic/detail.py
4@@ -58,8 +58,9 @@
5         `get_object` is overridden.
6         """
7         if self.queryset is None:
8-            if self.model:
9-                return self.model._default_manager.all()
10+            model = self.get_model()
11+            if model:
12+                return model._default_manager.all()
13             else:
14                 raise ImproperlyConfigured(u"%(cls)s is missing a queryset. Define "
15                                            u"%(cls)s.model, %(cls)s.queryset, or override "
16@@ -92,6 +93,9 @@
17             context[context_object_name] = self.object
18         return context
19 
20+    def get_model(self):
21+        return self.model
22+
23 
24 class BaseDetailView(SingleObjectMixin, View):
25     def get(self, request, **kwargs):
26@@ -132,12 +136,14 @@
27                 self.object._meta.object_name.lower(),
28                 self.template_name_suffix
29             ))
30-        elif hasattr(self, 'model') and hasattr(self.model, '_meta'):
31-            names.append("%s/%s%s.html" % (
32-                self.model._meta.app_label,
33-                self.model._meta.object_name.lower(),
34-                self.template_name_suffix
35-            ))
36+        elif hasattr(self, 'get_model'):
37+            model = self.get_model()
38+            if hasattr(model, '_meta'):
39+                names.append("%s/%s%s.html" % (
40+                    model._meta.app_label,
41+                    model._meta.object_name.lower(),
42+                    self.template_name_suffix
43+                ))
44         return names
45 
46 
47diff --git a/django/views/generic/edit.py b/django/views/generic/edit.py
48--- a/django/views/generic/edit.py
49+++ b/django/views/generic/edit.py
50@@ -75,17 +75,7 @@
51         if self.form_class:
52             return self.form_class
53         else:
54-            if self.model is not None:
55-                # If a model has been explicitly provided, use it
56-                model = self.model
57-            elif hasattr(self, 'object') and self.object is not None:
58-                # If this view is operating on a single object, use
59-                # the class of that object
60-                model = self.object.__class__
61-            else:
62-                # Try to get a queryset and extract the model class
63-                # from that
64-                model = self.get_queryset().model
65+            model = self.get_model()
66             return model_forms.modelform_factory(model)
67 
68     def get_form_kwargs(self):
69@@ -120,6 +110,16 @@
70             if context_object_name:
71                 context[context_object_name] = self.object
72         return context
73+       
74+    def get_model(self):
75+        if self.model:
76+            return self.model
77+        elif self.form_class and issubclass(self.form_class, model_forms.ModelForm):
78+            return self.form_class._meta.model
79+        elif hasattr(self, 'object') and self.object is not None:
80+            return self.object.__class__
81+        else:
82+            return self.get_queryset().model
83 
84 
85 class ProcessFormView(View):
86diff --git a/tests/regressiontests/generic_views/edit.py b/tests/regressiontests/generic_views/edit.py
87--- a/tests/regressiontests/generic_views/edit.py
88+++ b/tests/regressiontests/generic_views/edit.py
89@@ -75,6 +75,21 @@
90         self.assertRedirects(res, reverse('author_detail', kwargs={'pk': obj.pk}))
91         self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>'])
92 
93+    def test_create_with_only_form_class(self):
94+        res = self.client.get('/edit/artists/create/formclass/')
95+        self.assertEqual(res.status_code, 200)
96+        self.assertTrue(isinstance(res.context['form'], views.ArtistForm))
97+        self.assertFalse('object' in res.context)
98+        self.assertFalse('artist' in res.context)
99+        self.assertTemplateUsed(res, 'generic_views/artist_form.html')
100+       
101+        res = self.client.post('/edit/artists/create/formclass/',
102+                               {'name': 'Rene Magritte'})
103+        self.assertEqual(res.status_code, 302)
104+        artist = Artist.objects.get(name='Rene Magritte')
105+        self.assertRedirects(res, 'http://testserver/detail/artist/%d/' % artist.pk)
106+        self.assertQuerysetEqual(Artist.objects.all(), ['<Artist: Rene Magritte>'])
107+
108     def test_create_without_redirect(self):
109         try:
110             res = self.client.post('/edit/authors/create/naive/',
111diff --git a/tests/regressiontests/generic_views/forms.py b/tests/regressiontests/generic_views/forms.py
112--- a/tests/regressiontests/generic_views/forms.py
113+++ b/tests/regressiontests/generic_views/forms.py
114@@ -1,6 +1,6 @@
115 from django import forms
116 
117-from regressiontests.generic_views.models import Author
118+from regressiontests.generic_views.models import Author, Artist
119 
120 
121 class AuthorForm(forms.ModelForm):
122@@ -9,3 +9,10 @@
123 
124     class Meta:
125         model = Author
126+
127+
128+class ArtistForm(forms.ModelForm):
129+    name = forms.CharField()
130+
131+    class Meta:
132+        model = Artist
133diff --git a/tests/regressiontests/generic_views/urls.py b/tests/regressiontests/generic_views/urls.py
134--- a/tests/regressiontests/generic_views/urls.py
135+++ b/tests/regressiontests/generic_views/urls.py
136@@ -54,6 +54,8 @@
137     # Create/UpdateView
138     (r'^edit/artists/create/$',
139         views.ArtistCreate.as_view()),
140+    (r'^edit/artists/create/formclass/$',
141+        views.ArtistOnlyFormClassCreate.as_view()),
142     (r'^edit/artists/(?P<pk>\d+)/update/$',
143         views.ArtistUpdate.as_view()),
144 
145diff --git a/tests/regressiontests/generic_views/views.py b/tests/regressiontests/generic_views/views.py
146--- a/tests/regressiontests/generic_views/views.py
147+++ b/tests/regressiontests/generic_views/views.py
148@@ -5,7 +5,7 @@
149 from django.views import generic
150 
151 from regressiontests.generic_views.models import Artist, Author, Book, Page
152-from regressiontests.generic_views.forms import AuthorForm
153+from regressiontests.generic_views.forms import AuthorForm, ArtistForm
154 
155 
156 class CustomTemplateView(generic.TemplateView):
157@@ -77,6 +77,9 @@
158 class ArtistCreate(generic.CreateView):
159     model = Artist
160 
161+class ArtistOnlyFormClassCreate(generic.CreateView):
162+    form_class = ArtistForm
163+
164 
165 class NaiveAuthorCreate(generic.CreateView):
166     queryset = Author.objects.all()