Code

Ticket #10061: admin-urls.7.diff

File admin-urls.7.diff, 17.1 KB (added by Alex, 5 years ago)
Line 
1diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py
2index ed41c7f..8aff5a7 100644
3--- a/django/contrib/admin/options.py
4+++ b/django/contrib/admin/options.py
5@@ -217,13 +217,13 @@ class ModelAdmin(BaseModelAdmin):
6             url(r'^add/$',
7                 wrap(self.add_view),
8                 name='%sadmin_%s_%s_add' % info),
9-            url(r'^(.+)/history/$',
10+            url(r'^(?P<object_id>.+)/history/$',
11                 wrap(self.history_view),
12                 name='%sadmin_%s_%s_history' % info),
13-            url(r'^(.+)/delete/$',
14+            url(r'^(?P<object_id>.+)/delete/$',
15                 wrap(self.delete_view),
16                 name='%sadmin_%s_%s_delete' % info),
17-            url(r'^(.+)/$',
18+            url(r'^(?P<object_id>.+)/$',
19                 wrap(self.change_view),
20                 name='%sadmin_%s_%s_change' % info),
21         )
22@@ -437,6 +437,7 @@ class ModelAdmin(BaseModelAdmin):
23             'save_as': self.save_as,
24             'save_on_top': self.save_on_top,
25             'root_path': self.admin_site.root_path,
26+            'admin_site': self.admin_site.name,
27         })
28         return render_to_response(self.change_form_template or [
29             "admin/%s/%s/change_form.html" % (app_label, opts.object_name.lower()),
30@@ -571,6 +572,7 @@ class ModelAdmin(BaseModelAdmin):
31             'errors': helpers.AdminErrorList(form, formsets),
32             'root_path': self.admin_site.root_path,
33             'app_label': opts.app_label,
34+            'admin_site': self.admin_site.name,
35         }
36         context.update(extra_context or {})
37         return self.render_change_form(request, context, add=True)
38@@ -649,6 +651,7 @@ class ModelAdmin(BaseModelAdmin):
39             'inline_admin_formsets': inline_admin_formsets,
40             'errors': helpers.AdminErrorList(form, formsets),
41             'root_path': self.admin_site.root_path,
42+            'admin_site': self.admin_site.name,
43             'app_label': opts.app_label,
44         }
45         context.update(extra_context or {})
46@@ -681,6 +684,7 @@ class ModelAdmin(BaseModelAdmin):
47             'cl': cl,
48             'has_add_permission': self.has_add_permission(request),
49             'root_path': self.admin_site.root_path,
50+            'admin_site': self.admin_site.name,
51             'app_label': app_label,
52         }
53         context.update(extra_context or {})
54@@ -736,6 +740,7 @@ class ModelAdmin(BaseModelAdmin):
55             "perms_lacking": perms_needed,
56             "opts": opts,
57             "root_path": self.admin_site.root_path,
58+            'admin_site': self.admin_site.name,
59             "app_label": app_label,
60         }
61         context.update(extra_context or {})
62@@ -763,6 +768,7 @@ class ModelAdmin(BaseModelAdmin):
63             'module_name': capfirst(force_unicode(opts.verbose_name_plural)),
64             'object': obj,
65             'root_path': self.admin_site.root_path,
66+            'admin_site': self.admin_site.name,
67             'app_label': app_label,
68         }
69         context.update(extra_context or {})
70diff --git a/django/contrib/admin/sites.py b/django/contrib/admin/sites.py
71index 42ce296..d77eebd 100644
72--- a/django/contrib/admin/sites.py
73+++ b/django/contrib/admin/sites.py
74@@ -3,6 +3,7 @@ from django import http, template
75 from django.contrib.admin import ModelAdmin
76 from django.contrib.auth import authenticate, login
77 from django.db.models.base import ModelBase
78+from django.core.urlresolvers import reverse
79 from django.core.exceptions import ImproperlyConfigured
80 from django.shortcuts import render_to_response
81 from django.utils.functional import update_wrapper
82@@ -35,10 +36,7 @@ class AdminSite(object):
83     
84     def __init__(self, name=None):
85         self._registry = {} # model_class class -> admin_class instance
86-        # TODO Root path is used to calculate urls under the old root() method
87-        # in order to maintain backwards compatibility we are leaving that in
88-        # so root_path isn't needed, not sure what to do about this.
89-        self.root_path = 'admin/'
90+        self.root_path = None
91         if name is None:
92             name = ''
93         else:
94@@ -163,7 +161,7 @@ class AdminSite(object):
95                 name='%sadmin_index' % self.name),
96             url(r'^logout/$',
97                 wrap(self.logout),
98-                name='%sadmin_logout'),
99+                name='%sadmin_logout' % self.name),
100             url(r'^password_change/$',
101                 wrap(self.password_change),
102                 name='%sadmin_password_change' % self.name),
103@@ -197,8 +195,12 @@ class AdminSite(object):
104         Handles the "change password" task -- both form display and validation.
105         """
106         from django.contrib.auth.views import password_change
107+        if self.root_path is not None:
108+            url = '%spassword_change/done/' % self.root_path
109+        else:
110+            url = reverse('%sadmin_password_change_done' % self.name)
111         return password_change(request,
112-            post_change_redirect='%spassword_change/done/' % self.root_path)
113+            post_change_redirect=url)
114     
115     def password_change_done(self, request):
116         """
117@@ -328,6 +330,7 @@ class AdminSite(object):
118             'title': _('Site administration'),
119             'app_list': app_list,
120             'root_path': self.root_path,
121+            'admin_site': self.name
122         }
123         context.update(extra_context or {})
124         return render_to_response(self.index_template or 'admin/index.html', context,
125@@ -342,6 +345,7 @@ class AdminSite(object):
126             'app_path': request.get_full_path(),
127             'error_message': error_message,
128             'root_path': self.root_path,
129+            'admin_site': self.name,
130         }
131         context.update(extra_context or {})
132         return render_to_response(self.login_template or 'admin/login.html', context,
133@@ -388,6 +392,7 @@ class AdminSite(object):
134             'title': _('%s administration') % capfirst(app_label),
135             'app_list': [app_dict],
136             'root_path': self.root_path,
137+            'admin_site': self.name,
138         }
139         context.update(extra_context or {})
140         return render_to_response(self.app_index_template or 'admin/app_index.html', context,
141diff --git a/django/contrib/admin/templates/admin/base.html b/django/contrib/admin/templates/admin/base.html
142index e969d1b..623d769 100644
143--- a/django/contrib/admin/templates/admin/base.html
144+++ b/django/contrib/admin/templates/admin/base.html
145@@ -25,7 +25,36 @@
146         {% block branding %}{% endblock %}
147         </div>
148         {% if user.is_authenticated and user.is_staff %}
149-        <div id="user-tools">{% trans 'Welcome,' %} <strong>{% firstof user.first_name user.username %}</strong>. {% block userlinks %}{% url django-admindocs-docroot as docsroot %}{% if docsroot %}<a href="{{ docsroot }}">{% trans 'Documentation' %}</a> / {% endif %}<a href="{{ root_path }}password_change/">{% trans 'Change password' %}</a> / <a href="{{ root_path }}logout/">{% trans 'Log out' %}</a>{% endblock %}</div>
150+        <div id="user-tools">
151+            {% trans 'Welcome,' %}
152+            <strong>
153+                {% firstof user.first_name user.username %}
154+            </strong>.
155+            {% block userlinks %}
156+                {% url django-admindocs-docroot as docsroot %}
157+                {% if docsroot %}
158+                    <a href="{{ docsroot }}">
159+                        {% trans 'Documentation' %}
160+                    </a> /
161+                {% endif %}
162+                {% url admin_site:admin_password_change as password_change_url %}
163+                {% if password_change_url %}
164+                    <a href="{{ password_change_url }}">
165+                {% else %}
166+                    <a href="{{ root_path }}password_change/">
167+                {% endif %}
168+                    {% trans 'Change password' %}
169+                </a> /
170+                {% url admin_site:admin_logout as logout_url %}
171+                {% if logout_url %}
172+                    <a href="{{ logout_url }}">
173+                {% else %}
174+                    <a href="{{ root_path }}logout/">
175+                {% endif %}
176+                    {% trans 'Log out' %}
177+                </a>
178+            {% endblock %}
179+        </div>
180         {% endif %}
181         {% block nav-global %}{% endblock %}
182     </div>
183diff --git a/django/contrib/auth/admin.py b/django/contrib/auth/admin.py
184index c5326b7..9a13205 100644
185--- a/django/contrib/auth/admin.py
186+++ b/django/contrib/auth/admin.py
187@@ -92,6 +92,7 @@ class UserAdmin(admin.ModelAdmin):
188             'save_as': False,
189             'username_help_text': self.model._meta.get_field('username').help_text,
190             'root_path': self.admin_site.root_path,
191+            'admin_site': self.admin_site.name,
192             'app_label': self.model._meta.app_label,           
193         }, context_instance=template.RequestContext(request))
194 
195@@ -122,6 +123,7 @@ class UserAdmin(admin.ModelAdmin):
196             'save_as': False,
197             'show_save': True,
198             'root_path': self.admin_site.root_path,
199+            'admin_site': self.admin_site.name,
200         }, context_instance=RequestContext(request))
201 
202 
203diff --git a/django/contrib/comments/views/moderation.py b/django/contrib/comments/views/moderation.py
204index 3334b09..880c6d7 100644
205--- a/django/contrib/comments/views/moderation.py
206+++ b/django/contrib/comments/views/moderation.py
207@@ -7,6 +7,7 @@ from django.core.paginator import Paginator, InvalidPage
208 from django.http import Http404
209 from django.contrib import comments
210 from django.contrib.comments import signals
211+from django.contrib import admin
212 
213 #@login_required
214 def flag(request, comment_id, next=None):
215@@ -185,7 +186,8 @@ def moderation_queue(request):
216         'previous': page - 1,
217         'pages': paginator.num_pages,
218         'hits' : paginator.count,
219-        'page_range' : paginator.page_range
220+        'page_range' : paginator.page_range,
221+        'admin_site': admin.site.name,
222     }, context_instance=template.RequestContext(request))
223 
224 moderation_queue = permission_required("comments.can_moderate")(moderation_queue)
225diff --git a/django/core/urlresolvers.py b/django/core/urlresolvers.py
226index 59dcdcb..7044842 100644
227--- a/django/core/urlresolvers.py
228+++ b/django/core/urlresolvers.py
229@@ -254,6 +254,8 @@ def resolve(path, urlconf=None):
230     return get_resolver(urlconf).resolve(path)
231 
232 def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None):
233+    if isinstance(viewname, basestring):
234+        viewname = ''.join(viewname.split(':'))
235     args = args or []
236     kwargs = kwargs or {}
237     if prefix is None:
238diff --git a/django/template/defaulttags.py b/django/template/defaulttags.py
239index 0911309..c72fb0b 100644
240--- a/django/template/defaulttags.py
241+++ b/django/template/defaulttags.py
242@@ -368,6 +368,14 @@ class URLNode(Node):
243 
244     def render(self, context):
245         from django.core.urlresolvers import reverse, NoReverseMatch
246+        view_name_parts = []
247+        for part in self.view_name[:-1]:
248+            try:
249+                view_name_parts.append(Variable(part).resolve(context))
250+            except VariableDoesNotExist:
251+                view_name_parts.append(part)
252+        view_name_parts.append(self.view_name[-1])
253+        view_name = ':'.join(view_name_parts)
254         args = [arg.resolve(context) for arg in self.args]
255         kwargs = dict([(smart_str(k,'ascii'), v.resolve(context))
256                        for k, v in self.kwargs.items()])
257@@ -379,11 +387,11 @@ class URLNode(Node):
258         # {% url ... as var %} construct in which cause return nothing.
259         url = ''
260         try:
261-            url = reverse(self.view_name, args=args, kwargs=kwargs)
262+            url = reverse(view_name, args=args, kwargs=kwargs)
263         except NoReverseMatch:
264             project_name = settings.SETTINGS_MODULE.split('.')[0]
265             try:
266-                url = reverse(project_name + '.' + self.view_name,
267+                url = reverse(project_name + '.' + view_name,
268                               args=args, kwargs=kwargs)
269             except NoReverseMatch:
270                 if self.asvar is None:
271@@ -1102,6 +1110,10 @@ def url(parser, token):
272         raise TemplateSyntaxError("'%s' takes at least one argument"
273                                   " (path to a view)" % bits[0])
274     viewname = bits[1]
275+    if ':' in viewname:
276+        viewname = viewname.split(':')
277+    else:
278+        viewname = [viewname]
279     args = []
280     kwargs = {}
281     asvar = None
282diff --git a/docs/ref/contrib/admin.txt b/docs/ref/contrib/admin.txt
283index 35bfde2..f15fe1c 100644
284--- a/docs/ref/contrib/admin.txt
285+++ b/docs/ref/contrib/admin.txt
286@@ -1186,4 +1186,53 @@ It possible to add additional views to the admin site in the same way one can
287 add them to ``ModelAdmins``.  This by using the ``get_urls()`` method on an
288 AdminSite in the same way as `described above`__
289 
290+.. note::
291+    Any view you render that uses the admin templates, or extends the base
292+    admin template should include in it's context a variable named
293+    ``admin_site`` that contains the ``AdminSite`` instances name, which for
294+    ``AdminSite`` instances exists at ``self.name`` and for ``ModelAdmin``
295+    instances exists at ``self.admin_site.name``.
296+
297 __ `get_urls(self)`_
298+
299+
300+Reversing Admin URLs
301+====================
302+
303+.. versionadded :: 1.1
304+    Before Django 1.1 it wasn't possible to reverse admin URLs.  In addition
305+    for this to work you need to be using the new Django 1.1 ``include()``
306+    syntax for setting up admin URLs.
307+
308+The following are the url names, and parameters for ``AdminSite`` urls, all
309+url names are prefixed with the ``AdminSite`` instace's name, followed by an
310+underscore, so if an ``AdminSite`` was named ``"user_admin"`` it's urls names
311+would be prefixed with ``"user_admin_"``, the default ``AdminSite``'s name is
312+``''`` however it's names *do not* have the trailing underscore:
313+
314+    ======================  =============================== =============
315+    Page                    URL name                        Parameters
316+    ======================  =============================== =============
317+    Index                   ``admin_index``
318+    Logout                  ``admin_logout``
319+    Password change         ``admin_password_change``
320+    Password change done    ``admin_password_change_done``
321+    i18n javascript         ``admin_jsi18n``
322+    Application index page  ``admin_app_list``              ``app_label``
323+    ======================  =============================== =============
324+
325+The remaining urls are for ``ModelAdmin`` instances, these too are all prefixed
326+with the ``AdminSite``'s name(with the same caviets as the ``Adminsite``, and
327+``app_label`` and ``model_name`` are the lowercase versions of the
328+application's name and the model's name:
329+
330+    ======================  =====================================================   =============
331+    Page                    URL name                                                Parameters
332+    ======================  =====================================================   =============
333+    Changelist              ``admin_{{ app_label }}_{{ model_name }}_changelist``
334+    Add                     ``admin_{{ app_label }}_{{ model_name }}_add``
335+    History                 ``admin_{{ app_label }}_{{ model_name }}_history``      ``object_id``
336+    Delete                  ``admin_{{ app_label }}_{{ model_name }}_delete``       ``object_id``
337+    Change                  ``admin_{{ app_label }}_{{ model_name }}_change``       ``object_id``
338+    ======================  =====================================================   =============
339+
340diff --git a/tests/regressiontests/admin_views/tests.py b/tests/regressiontests/admin_views/tests.py
341index 39daf11..52ce268 100644
342--- a/tests/regressiontests/admin_views/tests.py
343+++ b/tests/regressiontests/admin_views/tests.py
344@@ -172,6 +172,11 @@ class AdminViewBasicTest(TestCase):
345         self.assertRedirects(response, '/test_admin/%s/admin_views/thing/?e=1' % self.urlbit)       
346         response = self.client.get('/test_admin/%s/admin_views/thing/' % self.urlbit, {'color__id__exact': 'StringNotInteger!'})
347         self.assertRedirects(response, '/test_admin/%s/admin_views/thing/?e=1' % self.urlbit)
348+   
349+    def testLogoutAndPasswordChangeURLs(self):
350+        response = self.client.get('/test_admin/%s/admin_views/article/' % self.urlbit)
351+        self.failIf('<a href="/test_admin/%s/logout/">' % self.urlbit not in response.content)
352+        self.failIf('<a href="/test_admin/%s/password_change/">' % self.urlbit not in response.content)
353 
354 class CustomModelAdminTest(AdminViewBasicTest):
355     urlbit = "admin2"
356diff --git a/tests/urls.py b/tests/urls.py
357index 43806de..a192f16 100644
358--- a/tests/urls.py
359+++ b/tests/urls.py
360@@ -20,13 +20,14 @@ urlpatterns = patterns('',
361 
362     # test urlconf for middleware tests
363     (r'^middleware/', include('regressiontests.middleware.urls')),
364+
365+    # admin widget tests
366+    (r'widget_admin/', include('regressiontests.admin_widgets.urls')),
367     
368     # admin view tests
369     (r'^test_admin/', include('regressiontests.admin_views.urls')),
370     (r'^generic_inline_admin/', include('regressiontests.generic_inline_admin.urls')),
371     
372-    # admin widget tests
373-    (r'widget_admin/', include('regressiontests.admin_widgets.urls')),
374 
375     (r'^utils/', include('regressiontests.utils.urls')),
376