Code

Ticket #6735: new-generic-views.3.diff

File new-generic-views.3.diff, 12.4 KB (added by jkocherhans, 6 years ago)
Line 
1diff --git a/django/views/generic/create_update.py b/django/views/generic/create_update.py
2index 46e92fe..e9a2dc9 100644
3--- a/django/views/generic/create_update.py
4+++ b/django/views/generic/create_update.py
5@@ -7,6 +7,196 @@ from django.template import RequestContext
6 from django.http import Http404, HttpResponse, HttpResponseRedirect
7 from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
8 from django.utils.translation import ugettext
9+from django import newforms as forms
10+from django.newforms.models import ModelFormMetaclass, ModelForm
11+
12+
13+# New-sytle, class based generic views #######################################
14+
15+class BaseView(object):
16+    """
17+    Base class for generic object creation and update view.
18+
19+    Templates: ``<app_label>/<model_name>_form.html``
20+    Context:
21+        form
22+            the ``ModelForm`` instance for the object
23+    """
24+    def __init__(self, model, post_save_redirect=None):
25+        self.model = model
26+        self.post_save_redirect = None
27+
28+    def __call__(self, request):
29+        return self.main(request, self.get_instance(request))
30+
31+    def main(self, request, instance):
32+        Form = self.get_form(request)
33+        if request.POST:
34+            form = Form(request.POST, request.FILES, instance=instance)
35+            if form.is_valid():
36+                new_object = self.save(request, form)
37+                return self.on_success(request, new_object)
38+        else:
39+            form = Form()
40+        rendered_template = self.get_rendered_template(request, instance, form)
41+        return HttpResponse(rendered_template)
42+
43+    def get_form(self, request):
44+        """
45+        Returns a ``ModelForm`` class to be used in this view.
46+        """
47+        # TODO: we should be able to construct a ModelForm without creating
48+        # and passing in a temporary inner class
49+        class Meta:
50+            model = self.model
51+        class_name = self.model.__name__ + 'Form'
52+        return ModelFormMetaclass(class_name, (ModelForm,), {'Meta': Meta})
53+
54+    def get_context(self, request, instance, form=None):
55+        """
56+        Returns a ``Context`` instance to be used when rendering this view.
57+        """
58+        return RequestContext(request, {'form': form, 'object': instance})
59+
60+    def get_template(self, request):
61+        """
62+        Returns the template to be used when rendering this view. Those who
63+        wish to use a custom template loader should do so here.
64+        """
65+        opts = self.model._meta
66+        template_name = "%s/%s_form.html" % (opts.app_label, opts.object_name.lower())
67+        return loader.get_template(template_name)
68+
69+    def get_rendered_template(self, request, instance, form=None):
70+        """
71+        Returns a rendered template. This will be passed as the sole argument
72+        to HttpResponse()
73+        """
74+        template = self.get_template(request)
75+        context = self.get_context(request, instance, form)
76+        return template.render(context)
77+
78+    def save(self, request, form):
79+        """
80+        Saves the object represented by the given ``form``. This method will
81+        only be called if the form is valid, and should in most cases return
82+        an HttpResponseRediect. It's return value will be the return value
83+        for the view on success.
84+        """
85+        return form.save()
86+
87+    def on_success(self, request, new_object):
88+        """
89+        Returns an HttpResonse, generally an HttpResponse redirect. This will
90+        be the final return value of the view and will only be called if the
91+        object was saved successfuly.
92+        """
93+        if request.user.is_authenticated():
94+            message = self.get_message(request, new_object)
95+            request.user.message_set.create(message=message)
96+        # Redirect to the new object: first by trying post_save_redirect,
97+        # then by obj.get_absolute_url; fail if neither works.
98+        if self.post_save_redirect:
99+            return HttpResponseRedirect(post_save_redirect % new_object.__dict__)
100+        elif hasattr(new_object, 'get_absolute_url'):
101+            return HttpResponseRedirect(new_object.get_absolute_url())
102+        else:
103+            raise ImproperlyConfigured("No URL to redirect to from generic create view.")
104+
105+class AddView(BaseView):
106+    def get_instance(self, request):
107+        """
108+        Returns the object instance to create.
109+        """
110+        return self.model()
111+
112+    def get_message(self, request, new_object):
113+        return ugettext("The %(verbose_name)s was created successfully.") % {"verbose_name": self.model._meta.verbose_name}
114+
115+class ChangeView(BaseView):
116+    def __init__(self, model, post_save_redirect=None, slug_field='slug'):
117+        self.slug_field = slug_field
118+        super(ChangeView, self).__init__(model, post_save_redirect=post_save_redirect)
119+
120+    def __call__(self, request, object_id=None, slug=None):
121+        return self.main(request, self.get_instance(request, object_id, slug))
122+
123+    def get_query_set(self, request):
124+        """
125+        Returns a queryset to use when trying to look up the object to change.
126+        """
127+        return self.model._default_manager.get_query_set()
128+
129+    def get_instance(self, request, object_id=None, slug=None):
130+        """
131+        Returns the object to be changed, or raises a 404 if it doesn't exist.
132+        """
133+        # Look up the object to be edited
134+        lookup_kwargs = {}
135+        if object_id:
136+            lookup_kwargs['pk'] = object_id
137+        elif slug and self.slug_field:
138+            lookup_kwargs['%s__exact' % slug_field] = slug
139+        else:
140+            raise AttributeError("Generic view must be called with either an object_id or a slug/slug_field")
141+        try:
142+            return self.get_query_set(request).get(**lookup_kwargs)
143+        except ObjectDoesNotExist:
144+            raise Http404, "No %s found for %s" % (self.model._meta.verbose_name, lookup_kwargs)
145+
146+    def get_message(self, request, new_object):
147+        return ugettext("The %(verbose_name)s was updated successfully.") % {"verbose_name": self.model._meta.verbose_name}
148+
149+class DeleteView(ChangeView):
150+    def __init__(self, model, post_save_redirect=None, slug_field='slug'):
151+        self.model = model
152+        self.slug_field = slug_field
153+        self.post_save_redirect = post_save_redirect
154+
155+    def main(self, request, instance):
156+        if request.method == 'POST':
157+            self.delete(instance)
158+            return self.on_success(request, instance)
159+        rendered_template = self.get_rendered_template(request, instance)
160+        response = HttpResponse(rendered_template)
161+        populate_xheaders(request, response, self.model, instance.pk)
162+        return response
163+
164+    def get_context(self, request, instance, form=None):
165+        """
166+        Returns a ``Context`` instance to be used when rendering this view.
167+        """
168+        return RequestContext(request, {'object': instance})
169+
170+    def get_template(self, request):
171+        opts = self.model._meta
172+        template_name = "%s/%s_confirm_delete.html" % (opts.app_label, opts.object_name.lower())
173+        return loader.get_template(template_name)
174+
175+    def delete(request, instance):
176+        """
177+        Deletes the given instance. Subclasses that wish to veto deletion
178+        should do so here.
179+        """
180+        instance.delete()
181+
182+    def on_success(self, request, new_object):
183+        """
184+        Redirects to self.post_save_redirect after setting a message if the
185+        user is logged in.
186+       
187+        This method is only called if saving the object was successful.
188+        """
189+        if request.user.is_authenticated():
190+            message = self.get_message(request, new_object)
191+            request.user.message_set.create(message=message)
192+        return HttpResponseRedirect(self.post_save_redirect)
193+
194+    def get_message(self, request, new_object):
195+        return ugettext("The %(verbose_name)s was deleted.") % {"verbose_name": model._meta.verbose_name}
196+
197+
198+# Classic generic views ######################################################
199 
200 def create_object(request, model, template_name=None,
201         template_loader=loader, extra_context=None, post_save_redirect=None,
202diff --git a/tests/regressiontests/views/tests/__init__.py b/tests/regressiontests/views/tests/__init__.py
203index 2c8c5b4..f0f6f59 100644
204--- a/tests/regressiontests/views/tests/__init__.py
205+++ b/tests/regressiontests/views/tests/__init__.py
206@@ -1,4 +1,5 @@
207 from defaults import *
208 from i18n import *
209 from static import *
210+from generic.create_update import *
211 from generic.date_based import *
212\ No newline at end of file
213diff --git a/tests/regressiontests/views/tests/generic/create_update.py b/tests/regressiontests/views/tests/generic/create_update.py
214new file mode 100644
215index 0000000..7cdbb9e
216--- /dev/null
217+++ b/tests/regressiontests/views/tests/generic/create_update.py
218@@ -0,0 +1,44 @@
219+# coding: utf-8
220+from django.test import TestCase
221+from regressiontests.views.models import Article, Author
222+
223+class AddViewTest(TestCase):
224+
225+    def test_initial(self):
226+        response = self.client.get('/views/create_update/add/')
227+        self.assertEqual(response.status_code, 200)
228+        self.assertEqual(response.context['form']._meta.model, Author)
229+        self.assertEqual(response.context['object'].name, "")
230+
231+    def test_submit(self):
232+        response = self.client.post('/views/create_update/add/', {
233+            'name': 'Boris',
234+        })
235+        self.assertEqual(response.status_code, 302)
236+
237+class ChangeViewTest(TestCase):
238+    fixtures = ['testdata.json']
239+
240+    def test_initial(self):
241+        response = self.client.get('/views/create_update/1/change/')
242+        self.assertEqual(response.status_code, 200)
243+        self.assertEqual(response.context['form']._meta.model, Author)
244+        self.assertEqual(response.context['object'].name, "Boris")
245+
246+    def test_submit(self):
247+        response = self.client.post('/views/create_update/1/change/', {
248+            'name': 'Jack Kerouac',
249+        })
250+        self.assertEqual(response.status_code, 302)
251+
252+class DeleteViewTest(TestCase):
253+    fixtures = ['testdata.json']
254+
255+    def test_initial(self):
256+        response = self.client.get('/views/create_update/1/delete/')
257+        self.assertEqual(response.status_code, 200)
258+        self.assertEqual(response.context['object'].name, "Boris")
259+
260+    def test_submit(self):
261+        response = self.client.post('/views/create_update/1/delete/', {})
262+        self.assertEqual(response.status_code, 302)
263diff --git a/tests/regressiontests/views/urls.py b/tests/regressiontests/views/urls.py
264index 5ef0c51..ebd5721 100644
265--- a/tests/regressiontests/views/urls.py
266+++ b/tests/regressiontests/views/urls.py
267@@ -1,6 +1,7 @@
268 from os import path
269 
270 from django.conf.urls.defaults import *
271+from django.views.generic.create_update import AddView, ChangeView, DeleteView
272 
273 from models import *
274 import views
275@@ -9,6 +10,10 @@ base_dir = path.dirname(path.abspath(__file__))
276 media_dir = path.join(base_dir, 'media')
277 locale_dir = path.join(base_dir, 'locale')
278 
279+author_add = AddView(Author)
280+author_change = ChangeView(Author)
281+author_delete = DeleteView(Author)
282+
283 js_info_dict = {
284     'domain': 'djangojs',
285     'packages': ('regressiontests.views',),
286@@ -34,8 +39,14 @@ urlpatterns = patterns('',
287     
288     # Static views
289     (r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': media_dir}),
290-   
291-       # Date-based generic views
292+
293+    # Create/Update generic views
294+    (r'create_update/add/', author_add),
295+    (r'create_update/(?P<object_id>\d+)/change/', author_change),
296+    (r'create_update/(?P<object_id>\d+)/delete/', author_delete),
297+
298+
299+    # Date-based generic views
300     (r'^date_based/object_detail/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<slug>[-\w]+)/$',
301         'django.views.generic.date_based.object_detail',
302         dict(slug_field='slug', **date_based_info_dict)),
303diff --git a/tests/templates/views/author_confirm_delete.html b/tests/templates/views/author_confirm_delete.html
304new file mode 100644
305index 0000000..3f8ff55
306--- /dev/null
307+++ b/tests/templates/views/author_confirm_delete.html
308@@ -0,0 +1 @@
309+This template intentionally left blank
310\ No newline at end of file
311diff --git a/tests/templates/views/author_form.html b/tests/templates/views/author_form.html
312new file mode 100644
313index 0000000..3f8ff55
314--- /dev/null
315+++ b/tests/templates/views/author_form.html
316@@ -0,0 +1 @@
317+This template intentionally left blank
318\ No newline at end of file