Code

Ticket #6470: admin-urlpatterns-6470.2.diff

File admin-urlpatterns-6470.2.diff, 15.5 KB (added by Alex, 6 years ago)

Latest version, full tests pass, and should be backwards compatible, updated docs

Line 
1diff --git a/django/conf/project_template/urls.py b/django/conf/project_template/urls.py
2index af1d1db..dfb49d3 100644
3--- a/django/conf/project_template/urls.py
4+++ b/django/conf/project_template/urls.py
5@@ -13,5 +13,5 @@ urlpatterns = patterns('',
6     # (r'^admin/doc/', include('django.contrib.admindocs.urls')),
7 
8     # Uncomment the next line to enable the admin:
9-    # (r'^admin/(.*)', admin.site.root),
10+    # (r'^admin/', include(admin.site.urls)),
11 )
12diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py
13index 019bfe9..39ab744 100644
14--- a/django/contrib/admin/options.py
15+++ b/django/contrib/admin/options.py
16@@ -1,3 +1,5 @@
17+import types
18+
19 from django import forms, template
20 from django.forms.formsets import all_valid
21 from django.forms.models import modelform_factory, inlineformset_factory
22@@ -5,7 +7,7 @@ from django.forms.models import BaseInlineFormSet
23 from django.contrib.contenttypes.models import ContentType
24 from django.contrib.admin import widgets
25 from django.contrib.admin import helpers
26-from django.contrib.admin.util import quote, unquote, flatten_fieldsets, get_deleted_objects
27+from django.contrib.admin.util import quote, unquote, flatten_fieldsets, get_deleted_objects, admin_perm_test
28 from django.core.exceptions import PermissionDenied
29 from django.db import models, transaction
30 from django.http import Http404, HttpResponse, HttpResponseRedirect
31@@ -196,6 +198,22 @@ class ModelAdmin(BaseModelAdmin):
32         else:
33             return self.change_view(request, unquote(url))
34 
35+    def _get_urls(self):
36+        from django.conf.urls.defaults import patterns, url
37+        urls_module = types.ModuleType('%s.urls' % self.__class__.__name__)
38+        info = self.model._meta.app_label, self.model._meta.module_name
39+        urlpatterns = patterns('',
40+            url(r'^$', lambda *args, **kwargs: self.changelist_view(*args, **kwargs), name='admin_%s_%s_changelist' % info),
41+            url(r'^add/$', lambda *args, **kwargs: self.add_view(*args, **kwargs), name='admin_%s_%s_add' % info),
42+            url(r'^(.+)/history/$', lambda *args, **kwargs: self.history_view(*args, **kwargs), name='admin_%s_%s_history' % info),
43+            url(r'^(.+)/delete/$', lambda *args, **kwargs: self.delete_view(*args, **kwargs), name='admin_%s_%s_delete' % info),
44+            url(r'^(.+)/$', lambda *args, **kwargs: self.change_view(*args, **kwargs), name='admin_%s_%s_change' % info),
45+        )
46+        urls_module.urlpatterns = urlpatterns
47+        return urls_module
48+    urls = property(_get_urls)
49+
50+
51     def _media(self):
52         from django.conf import settings
53 
54@@ -537,7 +555,7 @@ class ModelAdmin(BaseModelAdmin):
55         }
56         context.update(extra_context or {})
57         return self.render_change_form(request, context, add=True)
58-    add_view = transaction.commit_on_success(add_view)
59+    add_view = transaction.commit_on_success(admin_perm_test(add_view))
60 
61     def change_view(self, request, object_id, extra_context=None):
62         "The 'change' admin view for this model."
63@@ -545,7 +563,7 @@ class ModelAdmin(BaseModelAdmin):
64         opts = model._meta
65 
66         try:
67-            obj = model._default_manager.get(pk=object_id)
68+            obj = model._default_manager.get(pk=unquote(object_id))
69         except model.DoesNotExist:
70             # Don't raise Http404 just yet, because we haven't checked
71             # permissions yet. We don't want an unauthenticated user to be able
72@@ -615,7 +633,7 @@ class ModelAdmin(BaseModelAdmin):
73         }
74         context.update(extra_context or {})
75         return self.render_change_form(request, context, change=True, obj=obj)
76-    change_view = transaction.commit_on_success(change_view)
77+    change_view = transaction.commit_on_success(admin_perm_test(change_view))
78 
79     def changelist_view(self, request, extra_context=None):
80         "The 'change list' admin view for this model."
81@@ -651,6 +669,7 @@ class ModelAdmin(BaseModelAdmin):
82             'admin/%s/change_list.html' % app_label,
83             'admin/change_list.html'
84         ], context, context_instance=template.RequestContext(request))
85+    changelist_view = admin_perm_test(changelist_view)
86 
87     def delete_view(self, request, object_id, extra_context=None):
88         "The 'delete' admin view for this model."
89@@ -658,7 +677,7 @@ class ModelAdmin(BaseModelAdmin):
90         app_label = opts.app_label
91 
92         try:
93-            obj = self.model._default_manager.get(pk=object_id)
94+            obj = self.model._default_manager.get(pk=unquote(object_id))
95         except self.model.DoesNotExist:
96             # Don't raise Http404 just yet, because we haven't checked
97             # permissions yet. We don't want an unauthenticated user to be able
98@@ -673,7 +692,7 @@ class ModelAdmin(BaseModelAdmin):
99 
100         # Populate deleted_objects, a data structure of all related objects that
101         # will also be deleted.
102-        deleted_objects = [mark_safe(u'%s: <a href="../../%s/">%s</a>' % (escape(force_unicode(capfirst(opts.verbose_name))), quote(object_id), escape(obj))), []]
103+        deleted_objects = [mark_safe(u'%s: <a href="../../%s/">%s</a>' % (escape(force_unicode(capfirst(opts.verbose_name))), object_id, escape(obj))), []]
104         perms_needed = set()
105         get_deleted_objects(deleted_objects, perms_needed, request.user, obj, opts, 1, self.admin_site)
106 
107@@ -706,6 +725,7 @@ class ModelAdmin(BaseModelAdmin):
108             "admin/%s/delete_confirmation.html" % app_label,
109             "admin/delete_confirmation.html"
110         ], context, context_instance=template.RequestContext(request))
111+    delete_view = admin_perm_test(delete_view)
112 
113     def history_view(self, request, object_id, extra_context=None):
114         "The 'history' admin view for this model."
115@@ -733,6 +753,7 @@ class ModelAdmin(BaseModelAdmin):
116             "admin/%s/object_history.html" % app_label,
117             "admin/object_history.html"
118         ], context, context_instance=template.RequestContext(request))
119+    history_view = admin_perm_test(history_view)
120 
121 class InlineModelAdmin(BaseModelAdmin):
122     """
123diff --git a/django/contrib/admin/sites.py b/django/contrib/admin/sites.py
124index c16ab6a..a2a9aba 100644
125--- a/django/contrib/admin/sites.py
126+++ b/django/contrib/admin/sites.py
127@@ -1,7 +1,10 @@
128 import base64
129 import re
130+import types
131+
132 from django import http, template
133 from django.contrib.admin import ModelAdmin
134+from django.contrib.admin.util import admin_perm_test
135 from django.contrib.auth import authenticate, login
136 from django.db.models.base import ModelBase
137 from django.core.exceptions import ImproperlyConfigured
138@@ -36,6 +39,10 @@ class AdminSite(object):
139 
140     def __init__(self):
141         self._registry = {} # model_class class -> admin_class instance
142+        # TODO Root path is used to calculate urls under the old root() method
143+        # in order to maintain backwards compatibility we are leaving that in
144+        # so root_path isn't needed, not sure what to do about this.
145+        self.root_path = 'admin/'
146 
147     def register(self, model_or_iterable, admin_class=None, **options):
148         """
149@@ -121,6 +128,9 @@ class AdminSite(object):
150 
151         `url` is the remainder of the URL -- e.g. 'comments/comment/'.
152         """
153+        import warnings
154+        warnings.warn("Using AdminSite.root() is deprecated, you should \
155+            include(AdminSite.urls) instead", PendingDeprecationWarning)
156         if request.method == 'GET' and not request.path.endswith('/'):
157             return http.HttpResponseRedirect(request.path + '/')
158 
159@@ -159,7 +169,28 @@ class AdminSite(object):
160                 return self.app_index(request, url)
161 
162         raise http.Http404('The requested admin page does not exist.')
163-
164+   
165+    def _get_urls(self):
166+        from django.conf.urls.defaults import patterns, url, include
167+        from django.core.urlresolvers import RegexURLResolver
168+        urls_module = types.ModuleType('%s.urls' % self.__class__.__name__)
169+        urlpatterns = patterns('',
170+            url(r'^$', lambda *args, **kwargs: self.index(*args, **kwargs), name='admin_index'),
171+            url(r'^logout/$', lambda *args, **kwargs: self.logout(*args, **kwargs), name='admin_logout'),
172+            url(r'^password_change/$', lambda *args, **kwargs: self.password_change(*args, **kwargs), name='admin_password_change'),
173+            url(r'^password_change/done/$', lambda *args, **kwargs: self.password_change_done(*args, **kwargs), name='admin_password_change_done'),
174+            url(r'^jsi18n/$', lambda *args, **kwargs: self.i18n_javascript(*args, **kwargs), name='admin_jsi18n'),
175+            url('^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$', 'django.views.defaults.shortcut'),
176+            url('^(?P<app_label>\w+)/$', lambda *args, **kwargs: self.app_index(*args, **kwargs)),
177+        )
178+        for model, model_admin in self._registry.iteritems():
179+            urlpatterns += patterns('',
180+                url('^%s/%s/' % (model._meta.app_label, model._meta.module_name), include(model_admin.urls))
181+            )
182+        urls_module.urlpatterns = urlpatterns
183+        return urls_module
184+    urls = property(_get_urls)
185+   
186     def model_page(self, request, app_label, model_name, rest_of_url=None):
187         """
188         Handles the model-specific functionality of the admin site, delegating
189@@ -183,6 +214,7 @@ class AdminSite(object):
190         from django.contrib.auth.views import password_change
191         return password_change(request,
192             post_change_redirect='%spassword_change/done/' % self.root_path)
193+    passoword_change = admin_perm_test(password_change)
194 
195     def password_change_done(self, request):
196         """
197@@ -190,6 +222,7 @@ class AdminSite(object):
198         """
199         from django.contrib.auth.views import password_change_done
200         return password_change_done(request)
201+    password_change_done = admin_perm_test(password_change_done)
202 
203     def i18n_javascript(self, request):
204         """
205@@ -203,6 +236,7 @@ class AdminSite(object):
206         else:
207             from django.views.i18n import null_javascript_catalog as javascript_catalog
208         return javascript_catalog(request, packages='django.conf')
209+    i18n_javascript = admin_perm_test(i18n_javascript)
210 
211     def logout(self, request):
212         """
213@@ -317,7 +351,7 @@ class AdminSite(object):
214         return render_to_response(self.index_template or 'admin/index.html', context,
215             context_instance=template.RequestContext(request)
216         )
217-    index = never_cache(index)
218+    index = never_cache(admin_perm_test(index))
219 
220     def display_login_form(self, request, error_message='', extra_context=None):
221         request.session.set_test_cookie()
222@@ -377,6 +411,7 @@ class AdminSite(object):
223         return render_to_response(self.app_index_template or 'admin/app_index.html', context,
224             context_instance=template.RequestContext(request)
225         )
226+    app_index = admin_perm_test(app_index)
227 
228 # This global object represents the default admin site, for the common case.
229 # You can instantiate AdminSite in your own code to create a custom admin site.
230diff --git a/django/contrib/admin/util.py b/django/contrib/admin/util.py
231index 17213ea..2e184d9 100644
232--- a/django/contrib/admin/util.py
233+++ b/django/contrib/admin/util.py
234@@ -6,6 +6,17 @@ from django.utils.text import capfirst
235 from django.utils.encoding import force_unicode
236 from django.utils.translation import ugettext as _
237 
238+def admin_perm_test(func):
239+    def inner(admin_site_or_modeladmin, request, *args, **kwargs):
240+        if hasattr(admin_site_or_modeladmin, 'has_permission'):
241+            admin_site = admin_site_or_modeladmin
242+        else:
243+            admin_site = admin_site_or_modeladmin.admin_site
244+        if not admin_site.has_permission(request):
245+            return admin_site.login(request)
246+        # User has right permisssions show the view
247+        return func(admin_site_or_modeladmin, request, *args, **kwargs)
248+    return inner
249 
250 def quote(s):
251     """
252diff --git a/django/core/urlresolvers.py b/django/core/urlresolvers.py
253index 774e6d3..897cde2 100644
254--- a/django/core/urlresolvers.py
255+++ b/django/core/urlresolvers.py
256@@ -143,6 +143,8 @@ class RegexURLResolver(object):
257         # urlconf_name is a string representing the module containing urlconfs.
258         self.regex = re.compile(regex, re.UNICODE)
259         self.urlconf_name = urlconf_name
260+        if not isinstance(self.urlconf_name, basestring):
261+            self._urlconf_module = self.urlconf_name
262         self.callback = None
263         self.default_kwargs = default_kwargs or {}
264         self._reverse_dict = MultiValueDict()
265diff --git a/docs/intro/tutorial02.txt b/docs/intro/tutorial02.txt
266index b8cc1a0..48c2150 100644
267--- a/docs/intro/tutorial02.txt
268+++ b/docs/intro/tutorial02.txt
269@@ -57,7 +57,7 @@ activate the admin site for your installation, do these three things:
270               # (r'^admin/doc/', include('django.contrib.admindocs.urls')),
271 
272               # Uncomment the next line to enable the admin:
273-              **(r'^admin/(.*)', admin.site.root),**
274+              **(r'^admin/', include(admin.site.urls)),**
275           )
276 
277       (The bold lines are the ones that needed to be uncommented.)
278diff --git a/docs/ref/contrib/admin.txt b/docs/ref/contrib/admin.txt
279index 4f3f898..1ae78fd 100644
280--- a/docs/ref/contrib/admin.txt
281+++ b/docs/ref/contrib/admin.txt
282@@ -1027,7 +1027,7 @@ In this example, we register the default ``AdminSite`` instance
283     admin.autodiscover()
284 
285     urlpatterns = patterns('',
286-        ('^admin/(.*)', admin.site.root),
287+        ('^admin/', include(admin.site.urls)),
288     )
289 
290 Above we used ``admin.autodiscover()`` to automatically load the
291@@ -1041,15 +1041,13 @@ In this example, we register the ``AdminSite`` instance
292     from myproject.admin import admin_site
293 
294     urlpatterns = patterns('',
295-        ('^myadmin/(.*)', admin_site.root),
296+        ('^myadmin/', include(admin_site.urls)),
297     )
298 
299 There is really no need to use autodiscover when using your own ``AdminSite``
300 instance since you will likely be importing all the per-app admin.py modules
301 in your ``myproject.admin`` module.
302 
303-Note that the regular expression in the URLpattern *must* group everything in
304-the URL that comes after the URL root -- hence the ``(.*)`` in these examples.
305 
306 Multiple admin sites in the same URLconf
307 ----------------------------------------
308@@ -1068,6 +1066,6 @@ respectively::
309     from myproject.admin import basic_site, advanced_site
310 
311     urlpatterns = patterns('',
312-        ('^basic-admin/(.*)', basic_site.root),
313-        ('^advanced-admin/(.*)', advanced_site.root),
314+        ('^basic-admin/', include(basic_site.root)),
315+        ('^advanced-admin/', include(advanced_site.root)),
316     )
317diff --git a/tests/regressiontests/admin_views/tests.py b/tests/regressiontests/admin_views/tests.py
318index 5a10971..2d12360 100644
319--- a/tests/regressiontests/admin_views/tests.py
320+++ b/tests/regressiontests/admin_views/tests.py
321@@ -26,7 +26,7 @@ class AdminViewBasicTest(TestCase):
322         """
323         request = self.client.get('/test_admin/admin/admin_views/article/add')
324         self.assertRedirects(request,
325-            '/test_admin/admin/admin_views/article/add/'
326+            '/test_admin/admin/admin_views/article/add/', status_code=301
327         )
328     
329     def testBasicAddGet(self):
330diff --git a/tests/regressiontests/admin_views/urls.py b/tests/regressiontests/admin_views/urls.py
331index 4e5da48..02e0286 100644
332--- a/tests/regressiontests/admin_views/urls.py
333+++ b/tests/regressiontests/admin_views/urls.py
334@@ -5,5 +5,5 @@ import views
335 urlpatterns = patterns('',
336     (r'^admin/doc/', include('django.contrib.admindocs.urls')),
337     (r'^admin/secure-view/$', views.secure_view),
338-    (r'^admin/(.*)', admin.site.root),
339+    (r'^admin/', include(admin.site.urls)),
340 )