Fixed #15008 -- Replaced all calls in the admin to render_to_response with TemplateResponses for easier customization. Thanks to Chris Adams for the initial patch.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@16087 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Jannis Leidel 2011-04-22 18:17:16 +00:00
parent 13cfdb0d8b
commit c8092b840b
7 changed files with 97 additions and 67 deletions

View File

@ -2,12 +2,11 @@
Built-in, globally-available admin actions.
"""
from django import template
from django.core.exceptions import PermissionDenied
from django.contrib.admin import helpers
from django.contrib.admin.util import get_deleted_objects, model_ngettext
from django.db import router
from django.shortcuts import render_to_response
from django.template.response import TemplateResponse
from django.utils.encoding import force_unicode
from django.utils.translation import ugettext_lazy, ugettext as _
@ -76,10 +75,10 @@ def delete_selected(modeladmin, request, queryset):
}
# Display the confirmation page
return render_to_response(modeladmin.delete_selected_confirmation_template or [
return TemplateResponse(request, modeladmin.delete_selected_confirmation_template or [
"admin/%s/%s/delete_selected_confirmation.html" % (app_label, opts.object_name.lower()),
"admin/%s/delete_selected_confirmation.html" % app_label,
"admin/delete_selected_confirmation.html"
], context, context_instance=template.RequestContext(request))
], context, current_app=modeladmin.admin_site.name)
delete_selected.short_description = ugettext_lazy("Delete selected %(verbose_name_plural)s")

View File

@ -1,5 +1,5 @@
from functools import update_wrapper, partial
from django import forms, template
from django import forms
from django.forms.formsets import all_valid
from django.forms.models import (modelform_factory, modelformset_factory,
inlineformset_factory, BaseInlineFormSet)
@ -15,7 +15,8 @@ from django.db.models.related import RelatedObject
from django.db.models.fields import BLANK_CHOICE_DASH, FieldDoesNotExist
from django.db.models.sql.constants import LOOKUP_SEP, QUERY_TERMS
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.shortcuts import get_object_or_404
from django.template.response import SimpleTemplateResponse, TemplateResponse
from django.utils.decorators import method_decorator
from django.utils.datastructures import SortedDict
from django.utils.html import escape, escapejs
@ -708,12 +709,12 @@ class ModelAdmin(BaseModelAdmin):
form_template = self.add_form_template
else:
form_template = self.change_form_template
context_instance = template.RequestContext(request, current_app=self.admin_site.name)
return render_to_response(form_template or [
return TemplateResponse(request, form_template or [
"admin/%s/%s/change_form.html" % (app_label, opts.object_name.lower()),
"admin/%s/change_form.html" % app_label,
"admin/change_form.html"
], context, context_instance=context_instance)
], context, current_app=self.admin_site.name)
def response_add(self, request, obj, post_url_continue='../%s/'):
"""
@ -1074,7 +1075,9 @@ class ModelAdmin(BaseModelAdmin):
# something is screwed up with the database, so display an error
# page.
if ERROR_FLAG in request.GET.keys():
return render_to_response('admin/invalid_setup.html', {'title': _('Database error')})
return SimpleTemplateResponse('admin/invalid_setup.html', {
'title': _('Database error'),
})
return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1')
# If the request was POSTed, this might be a bulk action or a bulk
@ -1183,12 +1186,12 @@ class ModelAdmin(BaseModelAdmin):
'actions_selection_counter': self.actions_selection_counter,
}
context.update(extra_context or {})
context_instance = template.RequestContext(request, current_app=self.admin_site.name)
return render_to_response(self.change_list_template or [
return TemplateResponse(request, self.change_list_template or [
'admin/%s/%s/change_list.html' % (app_label, opts.object_name.lower()),
'admin/%s/change_list.html' % app_label,
'admin/change_list.html'
], context, context_instance=context_instance)
], context, current_app=self.admin_site.name)
@csrf_protect_m
@transaction.commit_on_success
@ -1244,12 +1247,12 @@ class ModelAdmin(BaseModelAdmin):
"app_label": app_label,
}
context.update(extra_context or {})
context_instance = template.RequestContext(request, current_app=self.admin_site.name)
return render_to_response(self.delete_confirmation_template or [
return TemplateResponse(request, self.delete_confirmation_template or [
"admin/%s/%s/delete_confirmation.html" % (app_label, opts.object_name.lower()),
"admin/%s/delete_confirmation.html" % app_label,
"admin/delete_confirmation.html"
], context, context_instance=context_instance)
], context, current_app=self.admin_site.name)
def history_view(self, request, object_id, extra_context=None):
"The 'history' admin view for this model."
@ -1272,12 +1275,11 @@ class ModelAdmin(BaseModelAdmin):
'app_label': app_label,
}
context.update(extra_context or {})
context_instance = template.RequestContext(request, current_app=self.admin_site.name)
return render_to_response(self.object_history_template or [
return TemplateResponse(request, self.object_history_template or [
"admin/%s/%s/object_history.html" % (app_label, opts.object_name.lower()),
"admin/%s/object_history.html" % app_label,
"admin/object_history.html"
], context, context_instance=context_instance)
], context, current_app=self.admin_site.name)
class InlineModelAdmin(BaseModelAdmin):
"""

View File

@ -9,7 +9,8 @@ from django.views.decorators.csrf import csrf_protect
from django.db.models.base import ModelBase
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from django.template.response import TemplateResponse
from django.utils.functional import update_wrapper
from django.utils.safestring import mark_safe
from django.utils.text import capfirst
from django.utils.translation import ugettext as _
@ -377,10 +378,9 @@ class AdminSite(object):
'root_path': self.root_path,
}
context.update(extra_context or {})
context_instance = template.RequestContext(request, current_app=self.name)
return render_to_response(self.index_template or 'admin/index.html', context,
context_instance=context_instance
)
return TemplateResponse(request, [
self.index_template or 'admin/index.html',
], context, current_app=self.name)
def app_index(self, request, app_label, extra_context=None):
user = request.user
@ -421,11 +421,11 @@ class AdminSite(object):
'root_path': self.root_path,
}
context.update(extra_context or {})
context_instance = template.RequestContext(request, current_app=self.name)
return render_to_response(self.app_index_template or ('admin/%s/app_index.html' % app_label,
'admin/app_index.html'), context,
context_instance=context_instance
)
return TemplateResponse(request, self.app_index_template or [
'admin/%s/app_index.html' % app_label,
'admin/app_index.html'
], context, current_app=self.name)
# This global object represents the default admin site, for the common case.
# You can instantiate AdminSite in your own code to create a custom admin site.

View File

@ -6,8 +6,8 @@ from django.contrib.auth.models import User, Group
from django.contrib import messages
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.shortcuts import get_object_or_404
from django.template.response import TemplateResponse
from django.utils.html import escape
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext, ugettext_lazy as _
@ -119,7 +119,7 @@ class UserAdmin(admin.ModelAdmin):
fieldsets = [(None, {'fields': form.base_fields.keys()})]
adminForm = admin.helpers.AdminForm(form, fieldsets, {})
return render_to_response(self.change_user_password_template or 'admin/auth/user/change_password.html', {
context = {
'title': _('Change password: %s') % escape(user.username),
'adminForm': adminForm,
'form': form,
@ -134,7 +134,11 @@ class UserAdmin(admin.ModelAdmin):
'save_as': False,
'show_save': True,
'root_path': self.admin_site.root_path,
}, context_instance=RequestContext(request))
}
return TemplateResponse(request, [
self.change_user_password_template or
'admin/auth/user/change_password.html'
], context, current_app=self.admin_site.name)
def response_add(self, request, obj, post_url_continue='../%s/'):
"""

View File

@ -3,8 +3,7 @@ import urlparse
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, QueryDict
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.template.response import TemplateResponse
from django.utils.http import base36_to_int
from django.utils.translation import ugettext as _
from django.views.decorators.cache import never_cache
@ -39,7 +38,7 @@ def login(request, template_name='registration/login.html',
if not redirect_to:
redirect_to = settings.LOGIN_REDIRECT_URL
# Security check -- don't allow redirection to a different
# Heavier security check -- don't allow redirection to a different
# host.
elif netloc and netloc != request.get_host():
redirect_to = settings.LOGIN_REDIRECT_URL
@ -64,9 +63,10 @@ def login(request, template_name='registration/login.html',
'site': current_site,
'site_name': current_site.name,
}
context.update(extra_context or {})
return render_to_response(template_name, context,
context_instance=RequestContext(request, current_app=current_app))
if extra_context is not None:
context.update(extra_context)
return TemplateResponse(request, template_name, context,
current_app=current_app)
def logout(request, next_page=None,
template_name='registration/logged_out.html',
@ -90,9 +90,10 @@ def logout(request, next_page=None,
'site_name': current_site.name,
'title': _('Logged out')
}
context.update(extra_context or {})
return render_to_response(template_name, context,
context_instance=RequestContext(request, current_app=current_app))
if extra_context is not None:
context.update(extra_context)
return TemplateResponse(request, template_name, context,
current_app=current_app)
else:
# Redirect to this page until the session has been cleared.
return HttpResponseRedirect(next_page or request.path)
@ -159,17 +160,19 @@ def password_reset(request, is_admin_site=False,
context = {
'form': form,
}
context.update(extra_context or {})
return render_to_response(template_name, context,
context_instance=RequestContext(request, current_app=current_app))
if extra_context is not None:
context.update(extra_context)
return TemplateResponse(request, template_name, context,
current_app=current_app)
def password_reset_done(request,
template_name='registration/password_reset_done.html',
current_app=None, extra_context=None):
context = {}
context.update(extra_context or {})
return render_to_response(template_name, context,
context_instance=RequestContext(request, current_app=current_app))
if extra_context is not None:
context.update(extra_context)
return TemplateResponse(request, template_name, context,
current_app=current_app)
# Doesn't need csrf_protect since no-one can guess the URL
@never_cache
@ -208,9 +211,10 @@ def password_reset_confirm(request, uidb36=None, token=None,
'form': form,
'validlink': validlink,
}
context.update(extra_context or {})
return render_to_response(template_name, context,
context_instance=RequestContext(request, current_app=current_app))
if extra_context is not None:
context.update(extra_context)
return TemplateResponse(request, template_name, context,
current_app=current_app)
def password_reset_complete(request,
template_name='registration/password_reset_complete.html',
@ -218,9 +222,10 @@ def password_reset_complete(request,
context = {
'login_url': settings.LOGIN_URL
}
context.update(extra_context or {})
return render_to_response(template_name, context,
context_instance=RequestContext(request, current_app=current_app))
if extra_context is not None:
context.update(extra_context)
return TemplateResponse(request, template_name, context,
current_app=current_app)
@csrf_protect
@login_required
@ -241,14 +246,16 @@ def password_change(request,
context = {
'form': form,
}
context.update(extra_context or {})
return render_to_response(template_name, context,
context_instance=RequestContext(request, current_app=current_app))
if extra_context is not None:
context.update(extra_context)
return TemplateResponse(request, template_name, context,
current_app=current_app)
def password_change_done(request,
template_name='registration/password_change_done.html',
current_app=None, extra_context=None):
context = {}
context.update(extra_context or {})
return render_to_response(template_name, context,
context_instance=RequestContext(request, current_app=current_app))
if extra_context is not None:
context.update(extra_context)
return TemplateResponse(request, template_name, context,
current_app=current_app)

View File

@ -1064,6 +1064,13 @@ provided some extra mapping data that would not otherwise be available::
return super(MyModelAdmin, self).change_view(request, object_id,
extra_context=my_context)
.. versionadded:: 1.4
These views now return :class:`~django.template.response.TemplateResponse`
instances which allow you to easily customize the response data before
rendering. For more details, see the
:doc:`TemplateResponse documentation </ref/template-response>`.
``ModelAdmin`` media definitions
--------------------------------

View File

@ -20,6 +20,7 @@ from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
from django.contrib.admin.views.main import IS_POPUP_VAR
from django.forms.util import ErrorList
import django.template.context
from django.template.response import TemplateResponse
from django.test import TestCase
from django.utils import formats
from django.utils.cache import get_max_age
@ -76,6 +77,7 @@ class AdminViewBasicTest(TestCase):
A smoke test to ensure GET on the add_view works.
"""
response = self.client.get('/test_admin/%s/admin_views/section/add/' % self.urlbit)
self.assertIsInstance(response, TemplateResponse)
self.assertEqual(response.status_code, 200)
def testAddWithGETArgs(self):
@ -91,6 +93,7 @@ class AdminViewBasicTest(TestCase):
A smoke test to ensure GET on the change_view works.
"""
response = self.client.get('/test_admin/%s/admin_views/section/1/' % self.urlbit)
self.assertIsInstance(response, TemplateResponse)
self.assertEqual(response.status_code, 200)
def testBasicEditGetStringPK(self):
@ -488,40 +491,47 @@ class CustomModelAdminTest(AdminViewBasicTest):
def testCustomAdminSiteLoginForm(self):
self.client.logout()
request = self.client.get('/test_admin/admin2/')
self.assertEqual(request.status_code, 200)
response = self.client.get('/test_admin/admin2/')
self.assertIsInstance(response, TemplateResponse)
self.assertEqual(response.status_code, 200)
login = self.client.post('/test_admin/admin2/', {
REDIRECT_FIELD_NAME: '/test_admin/admin2/',
LOGIN_FORM_KEY: 1,
'username': 'customform',
'password': 'secret',
})
self.assertIsInstance(login, TemplateResponse)
self.assertEqual(login.status_code, 200)
self.assertContains(login, 'custom form error')
def testCustomAdminSiteLoginTemplate(self):
self.client.logout()
request = self.client.get('/test_admin/admin2/')
self.assertIsInstance(request, TemplateResponse)
self.assertTemplateUsed(request, 'custom_admin/login.html')
self.assertTrue('Hello from a custom login template' in request.content)
def testCustomAdminSiteLogoutTemplate(self):
request = self.client.get('/test_admin/admin2/logout/')
self.assertIsInstance(request, TemplateResponse)
self.assertTemplateUsed(request, 'custom_admin/logout.html')
self.assertTrue('Hello from a custom logout template' in request.content)
def testCustomAdminSiteIndexViewAndTemplate(self):
request = self.client.get('/test_admin/admin2/')
self.assertIsInstance(request, TemplateResponse)
self.assertTemplateUsed(request, 'custom_admin/index.html')
self.assertTrue('Hello from a custom index template *bar*' in request.content)
def testCustomAdminSitePasswordChangeTemplate(self):
request = self.client.get('/test_admin/admin2/password_change/')
self.assertIsInstance(request, TemplateResponse)
self.assertTemplateUsed(request, 'custom_admin/password_change_form.html')
self.assertTrue('Hello from a custom password change form template' in request.content)
def testCustomAdminSitePasswordChangeDoneTemplate(self):
request = self.client.get('/test_admin/admin2/password_change/done/')
self.assertIsInstance(request, TemplateResponse)
self.assertTemplateUsed(request, 'custom_admin/password_change_done.html')
self.assertTrue('Hello from a custom password change done template' in request.content)
@ -631,7 +641,7 @@ class AdminViewPermissionsTest(TestCase):
self.assertFalse(login.context)
self.client.get('/test_admin/admin/logout/')
# Test if user enters email address
# Test if user enters e-mail address
request = self.client.get('/test_admin/admin/')
self.assertEqual(request.status_code, 200)
login = self.client.post('/test_admin/admin/', self.super_email_login)
@ -641,7 +651,7 @@ class AdminViewPermissionsTest(TestCase):
self.assertContains(login, "Please enter a correct username and password.")
new_user = User(username='jondoe', password='secret', email='super@example.com')
new_user.save()
# check to ensure if there are multiple email addresses a user doesn't get a 500
# check to ensure if there are multiple e-mail addresses a user doesn't get a 500
login = self.client.post('/test_admin/admin/', self.super_email_login)
self.assertContains(login, "Please enter a correct username and password.")
@ -1227,7 +1237,7 @@ class SecureViewTests(TestCase):
# make sure the view removes test cookie
self.assertEqual(self.client.session.test_cookie_worked(), False)
# Test if user enters email address
# Test if user enters e-mail address
request = self.client.get('/test_admin/admin/secure-view/')
self.assertEqual(request.status_code, 200)
login = self.client.post('/test_admin/admin/secure-view/', self.super_email_login)
@ -1237,7 +1247,7 @@ class SecureViewTests(TestCase):
self.assertContains(login, "Please enter a correct username and password.")
new_user = User(username='jondoe', password='secret', email='super@example.com')
new_user.save()
# check to ensure if there are multiple email addresses a user doesn't get a 500
# check to ensure if there are multiple e-mail addresses a user doesn't get a 500
login = self.client.post('/test_admin/admin/secure-view/', self.super_email_login)
self.assertContains(login, "Please enter a correct username and password.")
@ -1874,7 +1884,8 @@ class AdminActionsTest(TestCase):
'post': 'yes',
}
confirmation = self.client.post('/test_admin/admin/admin_views/subscriber/', action_data)
self.assertContains(confirmation, "Are you sure you want to delete the selected subscribers")
self.assertIsInstance(confirmation, TemplateResponse)
self.assertContains(confirmation, "Are you sure you want to delete the selected subscribers?")
self.assertTrue(confirmation.content.count(ACTION_CHECKBOX_NAME) == 2)
response = self.client.post('/test_admin/admin/admin_views/subscriber/', delete_confirmation_data)
self.assertEqual(Subscriber.objects.count(), 0)