Code

Ticket #12241: preserve_query_string_with_tests_2.diff

File preserve_query_string_with_tests_2.diff, 7.7 KB (added by batiste, 4 years ago)

Better tests that goes trough all the use case

Line 
1Index: django/contrib/admin/options.py
2===================================================================
3--- django/contrib/admin/options.py     (revision 13350)
4+++ django/contrib/admin/options.py     (working copy)
5@@ -24,6 +24,9 @@
6 from django.utils.translation import ungettext, ugettext_lazy
7 from django.utils.encoding import force_unicode
8 
9+import urllib
10+import urlparse
11+
12 HORIZONTAL, VERTICAL = 1, 2
13 # returns the <ul> class for a given radio_admin field
14 get_ul_class = lambda x: 'radiolist%s' % ((x == HORIZONTAL) and ' inline' or '')
15@@ -633,6 +636,20 @@
16             "admin/change_form.html"
17         ], context, context_instance=context_instance)
18 
19+    def redirect_with_query_string(self, request, url_continue, msg):
20+        """
21+        Handle a redirect URL and preserve the query string.
22+        """
23+        self.message_user(request, msg + ' ' + _("You may edit it again below."))
24+        string_dict = urlparse.parse_qs(request.META.get('QUERY_STRING'))
25+        if request.POST.has_key("_popup"):
26+            string_dict['_popup'] = 1
27+
28+        if string_dict:
29+            return url_continue + '?' + urllib.urlencode(string_dict)
30+       
31+        return url_continue
32+
33     def response_add(self, request, obj, post_url_continue='../%s/'):
34         """
35         Determines the HttpResponse for the add_view stage.
36@@ -644,12 +661,11 @@
37         # Here, we distinguish between different save types by checking for
38         # the presence of keys in request.POST.
39         if request.POST.has_key("_continue"):
40-            self.message_user(request, msg + ' ' + _("You may edit it again below."))
41-            if request.POST.has_key("_popup"):
42-                post_url_continue += "?_popup=1"
43-            return HttpResponseRedirect(post_url_continue % pk_value)
44+            url = post_url_continue % pk_value
45+            url = self.redirect_with_query_string(request, url, msg)
46+            return HttpResponseRedirect(url)
47 
48-        if request.POST.has_key("_popup"):
49+        if request.POST.has_key('_popup'):
50             return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % \
51                 # escape() calls force_unicode.
52                 (escape(pk_value), escape(obj)))
53@@ -677,11 +693,8 @@
54 
55         msg = _('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)}
56         if request.POST.has_key("_continue"):
57-            self.message_user(request, msg + ' ' + _("You may edit it again below."))
58-            if request.REQUEST.has_key('_popup'):
59-                return HttpResponseRedirect(request.path + "?_popup=1")
60-            else:
61-                return HttpResponseRedirect(request.path)
62+            url = self.redirect_with_query_string(request, request.path, msg)
63+            return HttpResponseRedirect(url)
64         elif request.POST.has_key("_saveasnew"):
65             msg = _('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % {'name': force_unicode(opts.verbose_name), 'obj': obj}
66             self.message_user(request, msg)
67Index: tests/regressiontests/admin_views/tests.py
68===================================================================
69--- tests/regressiontests/admin_views/tests.py  (revision 13350)
70+++ tests/regressiontests/admin_views/tests.py  (working copy)
71@@ -2,6 +2,7 @@
72 
73 import re
74 import datetime
75+import urlparse
76 from django.conf import settings
77 from django.core.files import temp as tempfile
78 from django.contrib.auth import admin # Register auth models with the admin.
79@@ -1623,6 +1624,86 @@
80             else:
81                 self.assertEqual(response.status_code, 404)
82 
83+class AdminResponseChangeTest(TestCase):
84+    fixtures = ['admin-views-users.xml']
85+
86+    def setUp(self):
87+        self.client.login(username='super', password='secret')
88+        self.data = {'title':"I Could Go Anywhere", 'content':"Versatile", 'date':datetime.datetime.now()}
89+        article = Article.objects.create(**self.data)
90+        self.pk = article.id
91+
92+    def test_response_add(self):
93+        """Add test for #12241: ModelAdmin.response_add should preserve the request
94+        query string after the redirection if the "save and continue" button
95+        is used within the admin."""
96+       
97+        self.data['_continue'] = True
98+        self.data['date_0'] = u"2008-03-18"
99+        self.data['date_1'] = u"11:54:58"
100+        response = self.client.post('/test_admin/admin/admin_views/article/%d/?test=1' % self.pk, self.data)
101+        self.assertEqual(response.status_code, 302)
102+        location = urlparse.urlparse(response['Location'])
103+        parsed_query_string = urlparse.parse_qs(location.query)
104+        self.assertTrue('test' in parsed_query_string.keys())
105+
106+        response = self.client.post('/test_admin/admin/admin_views/article/add/?test=1', self.data)
107+        self.assertEqual(response.status_code, 302)
108+        location = urlparse.urlparse(response['Location'])
109+        parsed_query_string = urlparse.parse_qs(location.query)
110+        self.assertTrue('test' in parsed_query_string.keys())
111+
112+        # test the popup redirection
113+        self.data['_popup'] = 1
114+        response = self.client.post('/test_admin/admin/admin_views/article/add/', self.data)
115+        self.assertEqual(response.status_code, 302)
116+        location = urlparse.urlparse(response['Location'])
117+        parsed_query_string = urlparse.parse_qs(location.query)
118+        self.assertTrue('_popup' in parsed_query_string.keys())
119+
120+        # test the popup redirection and another GET parameter
121+        response = self.client.post('/test_admin/admin/admin_views/article/add/?test=1', self.data)
122+        self.assertEqual(response.status_code, 302)
123+        location = urlparse.urlparse(response['Location'])
124+        parsed_query_string = urlparse.parse_qs(location.query)
125+        self.assertTrue('test' in parsed_query_string.keys())
126+        self.assertTrue('_popup' in parsed_query_string.keys())
127+
128+        # without anything
129+        self.data['date_0'] = u"2008-03-18"
130+        self.data['date_1'] = u"11:54:58"
131+        del self.data['_popup']
132+        response = self.client.post('/test_admin/admin/admin_views/article/add/', self.data)
133+        self.assertEqual(response.status_code, 302)
134+        location = urlparse.urlparse(response['Location'])
135+        parsed_query_string = urlparse.parse_qs(location.query)
136+        self.assertFalse('test' in parsed_query_string.keys())
137+        self.assertFalse('_popup' in parsed_query_string.keys())
138+
139+    def test_response_change(self):
140+        """Change test for issue #12241. ModelAdmin.response_change should
141+        preserve the query string."""
142+
143+        self.data['date_0'] = u"2008-03-18"
144+        self.data['date_1'] = u"11:54:58"
145+        self.data['_continue'] = True
146+
147+        response = self.client.post('/test_admin/admin/admin_views/article/%d/?test=1' % self.pk, self.data)
148+        self.assertEqual(response.status_code, 302)
149+        location = urlparse.urlparse(response['Location'])
150+        parsed_query_string = urlparse.parse_qs(location.query)
151+        self.assertTrue('test' in parsed_query_string.keys())
152+        self.assertFalse('_popup' in parsed_query_string.keys())
153+       
154+        response = self.client.post('/test_admin/admin/admin_views/article/%d/' % self.pk, self.data)
155+        self.assertEqual(response.status_code, 302)
156+        location = urlparse.urlparse(response['Location'])
157+        parsed_query_string = urlparse.parse_qs(location.query)
158+        self.assertFalse('test' in parsed_query_string.keys())
159+        self.assertFalse('_popup' in parsed_query_string.keys())
160+
161+
162+
163 class AdminInlineFileUploadTest(TestCase):
164     fixtures = ['admin-views-users.xml', 'admin-views-actions.xml']
165     urlbit = 'admin'