Ticket #12816: render_shortcut.6.diff
File render_shortcut.6.diff, 77.3 KB (added by , 14 years ago) |
---|
-
django/contrib/messages/middleware.py
diff -r 8343c0d86151 django/contrib/messages/middleware.py
a b 1 1 from django.conf import settings 2 2 from django.contrib.messages.storage import default_storage 3 3 4 5 4 class MessageMiddleware(object): 6 5 """ 7 6 Middleware that handles temporary messages. -
django/contrib/messages/tests/base.py
diff -r 8343c0d86151 django/contrib/messages/tests/base.py
a b 96 96 storage = self.get_storage() 97 97 self.assertFalse(storage.added_new) 98 98 storage.add(constants.INFO, 'Test message 1') 99 self.assert _(storage.added_new)99 self.assertTrue(storage.added_new) 100 100 storage.add(constants.INFO, 'Test message 2', extra_tags='tag') 101 101 self.assertEqual(len(storage), 2) 102 102 … … 173 173 for msg in data['messages']: 174 174 self.assertContains(response, msg) 175 175 176 def test_with_template_response(self): 177 settings.MESSAGE_LEVEL = constants.DEBUG 178 data = { 179 'messages': ['Test message %d' % x for x in xrange(10)], 180 } 181 show_url = reverse(self.urls + '.show_template_response') 182 183 for level in self.levels.keys(): 184 add_url = reverse(self.urls + '.add_template_response', 185 args=(level,)) 186 response = self.client.post(add_url, data, follow=True) 187 self.assertRedirects(response, show_url) 188 self.assertTrue('messages' in response.context) 189 for msg in data['messages']: 190 self.assertContains(response, msg) 191 192 # there shouldn't be any messages on second GET request 193 response = self.client.get(show_url) 194 for msg in data['messages']: 195 self.assertNotContains(response, msg) 196 176 197 def test_multiple_posts(self): 177 198 """ 178 199 Tests that messages persist properly when multiple POSTs are made -
django/contrib/messages/tests/urls.py
diff -r 8343c0d86151 django/contrib/messages/tests/urls.py
a b 2 2 from django.contrib import messages 3 3 from django.core.urlresolvers import reverse 4 4 from django.http import HttpResponseRedirect, HttpResponse 5 from django.shortcuts import render_to_response 5 from django.shortcuts import render_to_response, redirect 6 6 from django.template import RequestContext, Template 7 from django.template.response import TemplateResponse 7 8 9 TEMPLATE = """{% if messages %} 10 <ul class="messages"> 11 {% for message in messages %} 12 <li{% if message.tags %} class="{{ message.tags }}"{% endif %}> 13 {{ message }} 14 </li> 15 {% endfor %} 16 </ul> 17 {% endif %} 18 """ 8 19 9 20 def add(request, message_type): 10 21 # don't default to False here, because we want to test that it defaults … … 16 27 fail_silently=fail_silently) 17 28 else: 18 29 getattr(messages, message_type)(request, msg) 30 19 31 show_url = reverse('django.contrib.messages.tests.urls.show') 20 32 return HttpResponseRedirect(show_url) 21 33 34 def add_template_response(request, message_type): 35 for msg in request.POST.getlist('messages'): 36 getattr(messages, message_type)(request, msg) 37 return redirect('django.contrib.messages.tests.urls.show_template_response') 22 38 23 39 def show(request): 24 t = Template("""{% if messages %} 25 <ul class="messages"> 26 {% for message in messages %} 27 <li{% if message.tags %} class="{{ message.tags }}"{% endif %}> 28 {{ message }} 29 </li> 30 {% endfor %} 31 </ul> 32 {% endif %}""") 40 t = Template(TEMPLATE) 33 41 return HttpResponse(t.render(RequestContext(request))) 34 42 43 def show_template_response(request): 44 return TemplateResponse(request, Template(TEMPLATE)) 35 45 36 46 urlpatterns = patterns('', 37 47 ('^add/(debug|info|success|warning|error)/$', add), 38 48 ('^show/$', show), 49 ('^add-template-response/(debug|info|success|warning|error)/$', add_template_response), 50 ('^show-template-response/$', show_template_response), 39 51 ) -
django/core/handlers/base.py
diff -r 8343c0d86151 django/core/handlers/base.py
a b 21 21 def __init__(self): 22 22 self._request_middleware = self._view_middleware = self._response_middleware = self._exception_middleware = None 23 23 24 24 25 def load_middleware(self): 25 26 """ 26 27 Populate middleware lists from settings.MIDDLEWARE_CLASSES. … … 30 31 from django.conf import settings 31 32 from django.core import exceptions 32 33 self._view_middleware = [] 34 self._template_response_middleware = [] 33 35 self._response_middleware = [] 34 36 self._exception_middleware = [] 35 37 36 38 request_middleware = [] 37 39 for middleware_path in settings.MIDDLEWARE_CLASSES: 38 40 try: 39 dot = middleware_path.rindex('.') 40 except ValueError: 41 raise exceptions.ImproperlyConfigured('%s isn\'t a middleware module' % middleware_path) 42 mw_module, mw_classname = middleware_path[:dot], middleware_path[dot+1:] 43 try: 44 mod = import_module(mw_module) 45 except ImportError, e: 46 raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e)) 47 try: 48 mw_class = getattr(mod, mw_classname) 49 except AttributeError: 50 raise exceptions.ImproperlyConfigured('Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname)) 51 52 try: 53 mw_instance = mw_class() 41 mw_instance = get_middleware_instance(middleware_path) 54 42 except exceptions.MiddlewareNotUsed: 55 43 continue 56 44 … … 58 46 request_middleware.append(mw_instance.process_request) 59 47 if hasattr(mw_instance, 'process_view'): 60 48 self._view_middleware.append(mw_instance.process_view) 49 if hasattr(mw_instance, 'process_template_response'): 50 self._template_response_middleware.insert(0, mw_instance.process_template_response) 61 51 if hasattr(mw_instance, 'process_response'): 62 52 self._response_middleware.insert(0, mw_instance.process_response) 63 53 if hasattr(mw_instance, 'process_exception'): … … 162 152 urlresolvers.set_urlconf(None) 163 153 164 154 try: 155 # Apply template response middleware and the bake the response 156 # if the response can be baked 157 if hasattr(response, 'bake') and callable(response.bake): 158 for middleware_method in self._template_response_middleware: 159 response = middleware_method(request, response) 160 response.bake() 161 165 162 # Apply response middleware, regardless of the response 166 163 for middleware_method in self._response_middleware: 167 164 response = middleware_method(request, response) … … 240 237 return force_unicode(script_url[:-len(environ.get('PATH_INFO', ''))]) 241 238 return force_unicode(environ.get('SCRIPT_NAME', u'')) 242 239 240 def get_middleware_instance(middleware_path): 241 """ 242 Returns middleware instance 243 """ 244 try: 245 dot = middleware_path.rindex('.') 246 except ValueError: 247 raise exceptions.ImproperlyConfigured('%s isn\'t a middleware module' % middleware_path) 248 mw_module, mw_classname = middleware_path[:dot], middleware_path[dot+1:] 249 try: 250 mod = import_module(mw_module) 251 except ImportError, e: 252 raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e)) 253 try: 254 mw_class = getattr(mod, mw_classname) 255 except AttributeError: 256 raise exceptions.ImproperlyConfigured('Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname)) 257 258 return mw_class() 259 -
django/shortcuts/__init__.py
diff -r 8343c0d86151 django/shortcuts/__init__.py
a b 5 5 """ 6 6 7 7 from django.template import loader 8 from django.template.response import TemplateResponse 8 9 from django.http import HttpResponse, Http404 9 10 from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect 10 11 from django.db.models.manager import Manager … … 23 24 """ 24 25 Returns an HttpResponseRedirect to the apropriate URL for the arguments 25 26 passed. 26 27 27 28 The arguments could be: 28 29 29 30 * A model: the model's `get_absolute_url()` function will be called. 30 31 31 32 * A view name, possibly with arguments: `urlresolvers.reverse()` will 32 33 be used to reverse-resolve the name. 33 34 34 35 * A URL, which will be used as-is for the redirect location. 35 36 36 37 By default issues a temporary redirect; pass permanent=True to issue a 37 38 permanent redirect 38 39 """ … … 40 41 redirect_class = HttpResponsePermanentRedirect 41 42 else: 42 43 redirect_class = HttpResponseRedirect 43 44 44 45 # If it's a model, use get_absolute_url() 45 46 if hasattr(to, 'get_absolute_url'): 46 47 return redirect_class(to.get_absolute_url()) 47 48 48 49 # Next try a reverse URL resolution. 49 50 try: 50 51 return redirect_class(urlresolvers.reverse(to, args=args, kwargs=kwargs)) … … 55 56 # If this doesn't "feel" like a URL, re-raise. 56 57 if '/' not in to and '.' not in to: 57 58 raise 58 59 59 60 # Finally, fall back and assume it's a URL 60 61 return redirect_class(to) 61 62 … … 101 102 obj_list = list(queryset.filter(*args, **kwargs)) 102 103 if not obj_list: 103 104 raise Http404('No %s matches the given query.' % queryset.model._meta.object_name) 104 return obj_list 105 No newline at end of file 105 return obj_list 106 107 render = TemplateResponse -
new file django/template/response.py
diff -r 8343c0d86151 django/template/response.py
- + 1 from django.http import HttpResponse 2 from django.template import loader, Context, RequestContext 3 4 class ContentNotReadyError(Exception): 5 pass 6 7 class SimpleTemplateResponse(HttpResponse): 8 9 def __init__(self, template, context=None, mimetype=None, status=None, 10 content_type=None): 11 # These two properties were originally called 'template' and 'context' 12 # but django.test.client.Client was clobbering those leading to really 13 # tricky-to-debug problems 14 self.template_name = template 15 self.template_context = context 16 self.baked = False 17 18 # content argument doesn't make sense here because it will be replaced 19 # with rendered template so we always pass empty string in order to 20 # prevent errors and provide shorter signature. 21 super(SimpleTemplateResponse, self).__init__('', mimetype, status, 22 content_type) 23 24 def resolve_template(self, template): 25 "Accepts a template object, path-to-template or list of paths" 26 if isinstance(template, (list, tuple)): 27 return loader.select_template(template) 28 elif isinstance(template, basestring): 29 return loader.get_template(template) 30 else: 31 return template 32 33 def resolve_context(self, context): 34 "context can be a dictionary or a context object" 35 if isinstance(context, Context): 36 return context 37 else: 38 return Context(context) 39 40 def render(self): 41 template = self.resolve_template(self.template_name) 42 context = self.resolve_context(self.template_context) 43 content = template.render(context) 44 return content 45 46 def bake(self): 47 self._set_content(self.render()) 48 return self 49 50 def __iter__(self): 51 if not self.baked: 52 raise ContentNotReadyError('The response content is not ready. ' 53 'It must be baked before the iteration.') 54 return super(SimpleTemplateResponse, self).__iter__() 55 56 def _get_content(self): 57 if not self.baked: 58 raise ContentNotReadyError('The response content is not ready. ' 59 'It must be baked before the first access.') 60 return super(SimpleTemplateResponse, self)._get_content() 61 62 def _set_content(self, value): 63 "Overrides rendered content, unless you later call bake()" 64 super(SimpleTemplateResponse, self)._set_content(value) 65 self.baked = True 66 67 content = property(_get_content, _set_content) 68 69 class TemplateResponse(SimpleTemplateResponse): 70 71 def __init__(self, request, template, context=None, mimetype=None, 72 status=None, content_type=None): 73 # self.request gets over-written by django.test.client.Client - and 74 # unlike template_context and template_name the _request should not 75 # be considered part of the public API. 76 self._request = request 77 super(TemplateResponse, self).__init__( 78 template, context, mimetype, status, content_type) 79 80 def resolve_context(self, context): 81 if isinstance(context, Context): 82 return context 83 else: 84 return RequestContext(self._request, context) 85 86 def bake(response): 87 """ 88 Bakes response if it can be baked. HttpResponse instances are unaffected. 89 """ 90 if (hasattr(response, 'bake') and callable(response.bake)): 91 response.bake() -
django/test/testcases.py
diff -r 8343c0d86151 django/test/testcases.py
a b 484 484 Asserts that the template with the provided name was used in rendering 485 485 the response. 486 486 """ 487 487 488 if msg_prefix: 488 489 msg_prefix += ": " 489 490 -
django/views/generic/base.py
diff -r 8343c0d86151 django/views/generic/base.py
a b 2 2 from django import http 3 3 from django.core.exceptions import ImproperlyConfigured 4 4 from django.template import RequestContext, loader 5 from django.template.response import TemplateResponse 5 6 from django.utils.translation import ugettext_lazy as _ 6 7 from django.utils.functional import update_wrapper 7 8 from django.utils.log import getLogger … … 88 89 A mixin that can be used to render a template. 89 90 """ 90 91 template_name = None 92 template_response_class = TemplateResponse 91 93 92 def render_to_response(self, context ):94 def render_to_response(self, context, **response_kwargs): 93 95 """ 94 96 Returns a response with a template rendered with the given context. 95 97 """ 96 return self.get_response(self.render_template(context)) 97 98 def get_response(self, content, **httpresponse_kwargs): 99 """ 100 Construct an `HttpResponse` object. 101 """ 102 return http.HttpResponse(content, **httpresponse_kwargs) 103 104 def render_template(self, context): 105 """ 106 Render the template with a given context. 107 """ 108 context_instance = self.get_context_instance(context) 109 return self.get_template().render(context_instance) 110 111 def get_context_instance(self, context): 112 """ 113 Get the template context instance. Must return a Context (or subclass) 114 instance. 115 """ 116 return RequestContext(self.request, context) 117 118 def get_template(self): 119 """ 120 Get a ``Template`` object for the given request. 121 """ 122 names = self.get_template_names() 123 if not names: 124 raise ImproperlyConfigured(u"'%s' must provide template_name." 125 % self.__class__.__name__) 126 return self.load_template(names) 98 return self.template_response_class( 99 request = self.request, 100 template = self.get_template_names(), 101 context = context, 102 **response_kwargs 103 ) 127 104 128 105 def get_template_names(self): 129 106 """ 130 Return a list of template names to be used for the request. Must return131 a list. May not be called if get_template is overridden.107 Returns a list of template names to be used for the request. Must return 108 a list. May not be called if render_to_response is overridden. 132 109 """ 133 110 if self.template_name is None: 134 111 return [] 135 112 else: 136 113 return [self.template_name] 137 114 138 def load_template(self, names):139 """140 Load a list of templates using the default template loader.141 """142 return loader.select_template(names)143 144 115 145 116 class TemplateView(TemplateResponseMixin, View): 146 117 """ -
docs/index.txt
diff -r 8343c0d86151 docs/index.txt
a b 93 93 :doc:`View functions <topics/http/views>` | 94 94 :doc:`Shortcuts <topics/http/shortcuts>` 95 95 96 * **Reference:** :doc:`Request/response objects <ref/request-response>` 96 * **Reference:** 97 :doc:`Request/response objects <ref/request-response>` | 98 :doc:`TemplateResponse <ref/template-response>` 97 99 98 100 * **File uploads:** 99 101 :doc:`Overview <topics/http/file-uploads>` | -
docs/ref/class-based-views.txt
diff -r 8343c0d86151 docs/ref/class-based-views.txt
a b 76 76 77 77 The path to the template to use when rendering the view. 78 78 79 .. method:: render_to_response(context)79 .. attribute:: template_response_class 80 80 81 Returns a full composed HttpResponse instance, ready to be returned to 82 the user. 81 The response class to be returned by ``render_to_response`` method. 82 Default is 83 :class:`TemplateResponse <django.template.response.TemplateResponse>`. 84 The template and context of TemplateResponse instances can be 85 altered later (e.g. in 86 :ref:`template response middleware <template-response-middleware>`). 83 87 84 Calls :meth:`~TemplateResponseMixin.render_template()` to build the 85 content of the response, and 86 :meth:`~TemplateResponseMixin.get_response()` to construct the 87 :class:`~django.http.HttpResponse` object. 88 Create TemplateResponse subclass and pass set it to 89 ``template_response_class`` if you need custom template loading or 90 custom context object instantiation. 88 91 89 .. method:: get_response(content, **httpresponse_kwargs)92 .. method:: render_to_response(context, **response_kwargs) 90 93 91 Constructs the :class:`~django.http.HttpResponse` object around the 92 given content. If any keyword arguments are provided, they will be 93 passed to the constructor of the :class:`~django.http.HttpResponse` 94 instance. 94 Returns a ``self.template_response_class`` instance. 95 95 96 .. method:: render_template(context) 97 98 Calls :meth:`~TemplateResponseMixin.get_context_instance()` to obtain 99 the :class:`Context` instance to use for rendering, and calls 100 :meth:`TemplateReponseMixin.get_template()` to load the template that 101 will be used to render the final content. 102 103 .. method:: get_context_instance(context) 104 105 Turns the data dictionary ``context`` into an actual context instance 106 that can be used for rendering. 107 108 By default, constructs a :class:`~django.template.RequestContext` 109 instance. 110 111 .. method:: get_template() 96 If any keyword arguments are provided, they will be 97 passed to the constructor of the response instance. 112 98 113 99 Calls :meth:`~TemplateResponseMixin.get_template_names()` to obtain the 114 100 list of template names that will be searched looking for an existent … … 123 109 default implementation will return a list containing 124 110 :attr:`TemplateResponseMixin.template_name` (if it is specified). 125 111 126 .. method:: load_template(names)127 128 Loads and returns a template found by searching the list of ``names``129 for a match. Uses Django's default template loader.130 112 131 113 Single object mixins 132 114 -------------------- -
docs/ref/index.txt
diff -r 8343c0d86151 docs/ref/index.txt
a b 16 16 middleware 17 17 models/index 18 18 request-response 19 template-response 19 20 settings 20 21 signals 21 22 templates/index -
docs/ref/request-response.txt
diff -r 8343c0d86151 docs/ref/request-response.txt
a b 645 645 .. class:: HttpResponseServerError 646 646 647 647 Acts just like :class:`HttpResponse` but uses a 500 status code. 648 649 TemplateResponse 650 ---------------- 651 652 .. versionadded:: 1.3 653 654 See :doc:`TemplateResponse <ref/template-response>` for more. -
new file docs/ref/template-response.txt
diff -r 8343c0d86151 docs/ref/template-response.txt
- + 1 =========================================== 2 TemplateResponse and SimpleTemplateResponse 3 =========================================== 4 5 .. versionadded:: 1.3 6 7 .. module:: django.template.response 8 :synopsis: Classes dealing with lazy-rendered HTTP responses. 9 10 Quick overview 11 ============== 12 13 An HttpResponse with an opaque string as its content is hard to alter after 14 it is returned from a view. 15 16 Special HttpResponse subclass - TemplateResponse is introduced in Django to 17 solve this problem. It can keep a template and its context separate until 18 the very last moment when response middleware is applied and only then do 19 render a template. Such lazy template rendering is called 'baking' throught 20 the docs. 21 22 This way it is possible to add something to the view's context before it 23 blends in a template or to change the template that will be rendered. 24 25 This document explains the APIs for :class:`SimpleTemplateResponse` and 26 :class:`TemplateResponse` objects. 27 28 SimpleTemplateResponse objects 29 ============================== 30 31 .. class:: SimpleTemplateResponse() 32 33 Attributes 34 ---------- 35 36 .. attribute:: SimpleTemplateResponse.template_name 37 38 Template to be rendered. Accepts :class:`django.template.Template` object, 39 path to template or list of paths. 40 41 Example: ``['foo.html', 'bar.html']`` 42 43 .. attribute:: SimpleTemplateResponse.template_context 44 45 Context to be used with template. It can be a dictionary or a context 46 object. 47 48 Example: ``{'foo': 123}`` 49 50 51 Methods 52 ------- 53 54 .. method:: SimpleTemplateResponse.__init__(template, context=None, mimetype=None, status=None, content_type=None) 55 56 Instantiates an ``SimpleTemplateResponse`` object with the given template, 57 context, MIME type and HTTP status. 58 59 ``template`` is a full name of a template to use or sequence of 60 template names. :class:`django.template.Template` instances are also 61 accepted. 62 63 ``context`` is a dictionary of values to add to the template context. 64 By default, this is an empty dictionary; context objects are also 65 accepted as ``context`` values. 66 67 ``status`` is the HTTP Status code for the response. 68 69 ``content_type`` is an alias for ``mimetype``. Historically, this parameter 70 was only called ``mimetype``, but since this is actually the value included 71 in the HTTP ``Content-Type`` header, it can also include the character set 72 encoding, which makes it more than just a MIME type specification. 73 If ``mimetype`` is specified (not ``None``), that value is used. 74 Otherwise, ``content_type`` is used. If neither is given, the 75 ``DEFAULT_CONTENT_TYPE`` setting is used. 76 77 78 .. method:: SimpleTemplateResponse.resolve_context(context) 79 80 Accepts dictionary or a context object. 81 Returns :class:`django.template.Context` instance. 82 83 Override this method in order to customize context instantiation. 84 85 86 .. method:: SimpleTemplateResponse.resolve_template(template) 87 88 Accepts a full name of a template to use or sequence of template names. 89 :class:`django.template.Template` instances are also accepted. 90 Returns :class:`django.template.Template` instance to be rendered. 91 92 Override this method in order to customize template rendering. 93 94 .. method:: SimpleTemplateResponse.render(): 95 96 Renders a template instance returned by 97 :meth:`SimpleTemplateResponse.resolve_template` using the context instance 98 returned by :meth:`SimpleTemplateResponse.resolve_context` and returns the 99 rendered content. 100 101 .. method:: SimpleTemplateResponse.bake(): 102 103 Bakes the response by setting :attr:`response.content` to the result 104 returned by :meth:`SimpleTemplateResponse.render`. 105 106 The response is baked by Django during response middleware cycle. You should 107 only bake the response yourself if it is to be used outside the 108 request-response cycle (e.g. for debugging). It will be baked twice 109 otherwise. 110 111 112 113 TemplateResponse objects 114 ======================== 115 116 .. class:: TemplateResponse() 117 118 TemplateResponse is a subclass of 119 :class:`SimpleTemplateResponse <django.template.response.SimpleTemplateResponse>` 120 that uses RequestContext instead of Context. 121 122 .. method:: TemplateResponse.__init__(request, template, context=None, mimetype=None, status=None, content_type=None) 123 124 Instantiates an ``TemplateResponse`` object with the given template, 125 context, MIME type and HTTP status. 126 127 ``request`` is a HttpRequest instance. 128 129 ``template`` is a full name of a template to use or sequence of 130 template names. :class:`django.template.Template` instances are also 131 accepted. 132 133 ``context`` is a dictionary of values to add to the template context. 134 By default, this is an empty dictionary; context objects are also accepted 135 as ``context`` values. 136 137 ``status`` is the HTTP Status code for the response. 138 139 ``content_type`` is an alias for ``mimetype``. Historically, this parameter 140 was only called ``mimetype``, but since this is actually the value included 141 in the HTTP ``Content-Type`` header, it can also include the character set 142 encoding, which makes it more than just a MIME type specification. 143 If ``mimetype`` is specified (not ``None``), that value is used. 144 Otherwise, ``content_type`` is used. If neither is given, the 145 ``DEFAULT_CONTENT_TYPE`` setting is used. 146 -
docs/topics/http/middleware.txt
diff -r 8343c0d86151 docs/topics/http/middleware.txt
a b 120 120 classes are applied in reverse order, from the bottom up. This means classes 121 121 defined at the end of :setting:`MIDDLEWARE_CLASSES` will be run first. 122 122 123 .. _template-response-middleware: 124 125 ``process_template_response`` 126 ----------------------------- 127 128 .. versionadded:: 1.3 129 130 .. method:: process_template_response(self, request, response) 131 132 ``request`` is an :class:`~django.http.HttpRequest` object. ``response`` is the 133 :class:`~django.template.response.SimpleTemplateResponse` subclass (e.g. 134 :class:`~django.template.response.TemplateResponse`) object returned by a 135 Django view. 136 137 ``process_template_response()`` must return an 138 :class:`~django.template.response.SimpleTemplateResponse` (or it's subclass) 139 object. It could alter the given ``response`` by changing 140 ``response.template_name`` and ``response.template_context``, or it could 141 create and return a brand-new 142 :class:`~django.template.response.SimpleTemplateResponse` (or it's subclass) 143 instance. 144 145 ``process_template_response()`` method is called only on response instances that 146 can be baked. It is called before the ``process_response()`` method. 147 148 You shouldn't bake the response in ``process_template_response``. It 149 will be baked just before applying response middlewares. This way template 150 will be rendered exactly 1 time. 151 152 Middleware are run in reverse order during the response phase, which 153 includes process_template_response. 154 123 155 .. _exception-middleware: 124 156 125 157 ``process_exception`` -
docs/topics/http/shortcuts.txt
diff -r 8343c0d86151 docs/topics/http/shortcuts.txt
a b 12 12 "span" multiple levels of MVC. In other words, these functions/classes 13 13 introduce controlled coupling for convenience's sake. 14 14 15 ``render`` 16 ========== 17 18 .. function:: render(request, template[, context][, mimetype][, status][, content_type]) 19 20 Combines a given template with a given context dictionary and returns an 21 :class:`~django.template.response.TemplateResponse` object. 22 23 TODO 24 25 Examples 26 -------- 27 28 TODO 29 30 31 15 32 ``render_to_response`` 16 33 ====================== 17 34 -
tests/regressiontests/generic_views/base.py
diff -r 8343c0d86151 tests/regressiontests/generic_views/base.py
a b 156 156 rf = RequestFactory() 157 157 158 158 def _assert_about(self, response): 159 response.bake() 159 160 self.assertEqual(response.status_code, 200) 160 161 self.assertEqual(response.content, '<h1>About</h1>') 161 162 -
tests/regressiontests/middleware_exceptions/tests.py
diff -r 8343c0d86151 tests/regressiontests/middleware_exceptions/tests.py
a b 3 3 from django.test import TestCase 4 4 from django.core.signals import got_request_exception 5 5 from django.http import HttpResponse 6 6 from django.template.response import TemplateResponse 7 from django.template import Template 7 8 8 9 class TestException(Exception): 9 10 pass … … 15 16 self.process_request_called = False 16 17 self.process_view_called = False 17 18 self.process_response_called = False 19 self.process_template_response_called = False 18 20 self.process_exception_called = False 19 21 20 22 def process_request(self, request): … … 23 25 def process_view(self, request, view_func, view_args, view_kwargs): 24 26 self.process_view_called = True 25 27 28 def process_template_response(self, request, response): 29 self.process_template_response_called = True 30 return response 31 26 32 def process_response(self, request, response): 27 33 self.process_response_called = True 28 34 return response … … 47 53 super(ResponseMiddleware, self).process_response(request, response) 48 54 return HttpResponse('Response Middleware') 49 55 56 class TemplateResponseMiddleware(TestMiddleware): 57 def process_template_response(self, request, response): 58 super(TemplateResponseMiddleware, self).process_template_response(request, response) 59 return TemplateResponse(request, Template('Template Response Middleware')) 60 50 61 class ExceptionMiddleware(TestMiddleware): 51 62 def process_exception(self, request, exception): 52 63 super(ExceptionMiddleware, self).process_exception(request, exception) … … 65 76 super(BadViewMiddleware, self).process_view(request, view_func, view_args, view_kwargs) 66 77 raise TestException('Test View Exception') 67 78 79 class BadTemplateResponseMiddleware(TestMiddleware): 80 def process_template_response(self, request, response): 81 super(BadTemplateResponseMiddleware, self).process_template_response(request, response) 82 raise TestException('Test Template Response Exception') 83 68 84 class BadResponseMiddleware(TestMiddleware): 69 85 def process_response(self, request, response): 70 86 super(BadResponseMiddleware, self).process_response(request, response) … … 92 108 def _add_middleware(self, middleware): 93 109 self.client.handler._request_middleware.insert(0, middleware.process_request) 94 110 self.client.handler._view_middleware.insert(0, middleware.process_view) 111 self.client.handler._template_response_middleware.append(middleware.process_template_response) 95 112 self.client.handler._response_middleware.append(middleware.process_response) 96 113 self.client.handler._exception_middleware.append(middleware.process_exception) 97 114 … … 112 129 exception, value, tb = self.exceptions[i] 113 130 self.assertEquals(value.args, (error, )) 114 131 115 def assert_middleware_usage(self, middleware, request, view, response, exception):132 def assert_middleware_usage(self, middleware, request, view, template_response, response, exception): 116 133 self.assertEqual(middleware.process_request_called, request) 117 134 self.assertEqual(middleware.process_view_called, view) 135 self.assertEqual(middleware.process_template_response_called, template_response) 118 136 self.assertEqual(middleware.process_response_called, response) 119 137 self.assertEqual(middleware.process_exception_called, exception) 120 138 … … 131 149 self.assert_exceptions_handled('/middleware_exceptions/view/', []) 132 150 133 151 # Check that the right middleware methods have been invoked 134 self.assert_middleware_usage(pre_middleware, True, False, True, False)135 self.assert_middleware_usage(middleware, True, False, True, False)136 self.assert_middleware_usage(post_middleware, False, False, True, False)152 self.assert_middleware_usage(pre_middleware, True, False, False, True, False) 153 self.assert_middleware_usage(middleware, True, False, False, True, False) 154 self.assert_middleware_usage(post_middleware, False, False, False, True, False) 137 155 138 156 def test_process_view_middleware(self): 139 157 pre_middleware = TestMiddleware() … … 145 163 self.assert_exceptions_handled('/middleware_exceptions/view/', []) 146 164 147 165 # Check that the right middleware methods have been invoked 148 self.assert_middleware_usage(pre_middleware, True, True, True, False)149 self.assert_middleware_usage(middleware, True, True, True, False)150 self.assert_middleware_usage(post_middleware, True, False, True, False)166 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 167 self.assert_middleware_usage(middleware, True, True, False, True, False) 168 self.assert_middleware_usage(post_middleware, True, False, False, True, False) 151 169 152 170 def test_process_response_middleware(self): 153 171 pre_middleware = TestMiddleware() … … 159 177 self.assert_exceptions_handled('/middleware_exceptions/view/', []) 160 178 161 179 # Check that the right middleware methods have been invoked 162 self.assert_middleware_usage(pre_middleware, True, True, True, False) 163 self.assert_middleware_usage(middleware, True, True, True, False) 164 self.assert_middleware_usage(post_middleware, True, True, True, False) 180 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 181 self.assert_middleware_usage(middleware, True, True, False, True, False) 182 self.assert_middleware_usage(post_middleware, True, True, False, True, False) 183 184 def test_process_template_response_middleware(self): 185 pre_middleware = TestMiddleware() 186 middleware = TemplateResponseMiddleware() 187 post_middleware = TestMiddleware() 188 self._add_middleware(post_middleware) 189 self._add_middleware(middleware) 190 self._add_middleware(pre_middleware) 191 self.assert_exceptions_handled('/middleware_exceptions/template_response/', []) 192 193 # Check that the right middleware methods have been invoked 194 self.assert_middleware_usage(pre_middleware, True, True, True, True, False) 195 self.assert_middleware_usage(middleware, True, True, True, True, False) 196 self.assert_middleware_usage(post_middleware, True, True, True, True, False) 165 197 166 198 def test_process_exception_middleware(self): 167 199 pre_middleware = TestMiddleware() … … 173 205 self.assert_exceptions_handled('/middleware_exceptions/view/', []) 174 206 175 207 # Check that the right middleware methods have been invoked 176 self.assert_middleware_usage(pre_middleware, True, True, True, False)177 self.assert_middleware_usage(middleware, True, True, True, False)178 self.assert_middleware_usage(post_middleware, True, True, True, False)208 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 209 self.assert_middleware_usage(middleware, True, True, False, True, False) 210 self.assert_middleware_usage(post_middleware, True, True, False, True, False) 179 211 180 212 def test_process_request_middleware_not_found(self): 181 213 pre_middleware = TestMiddleware() … … 187 219 self.assert_exceptions_handled('/middleware_exceptions/not_found/', []) 188 220 189 221 # Check that the right middleware methods have been invoked 190 self.assert_middleware_usage(pre_middleware, True, False, True, False)191 self.assert_middleware_usage(middleware, True, False, True, False)192 self.assert_middleware_usage(post_middleware, False, False, True, False)222 self.assert_middleware_usage(pre_middleware, True, False, False, True, False) 223 self.assert_middleware_usage(middleware, True, False, False, True, False) 224 self.assert_middleware_usage(post_middleware, False, False, False, True, False) 193 225 194 226 def test_process_view_middleware_not_found(self): 195 227 pre_middleware = TestMiddleware() … … 201 233 self.assert_exceptions_handled('/middleware_exceptions/not_found/', []) 202 234 203 235 # Check that the right middleware methods have been invoked 204 self.assert_middleware_usage(pre_middleware, True, True, True, False) 205 self.assert_middleware_usage(middleware, True, True, True, False) 206 self.assert_middleware_usage(post_middleware, True, False, True, False) 236 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 237 self.assert_middleware_usage(middleware, True, True, False, True, False) 238 self.assert_middleware_usage(post_middleware, True, False, False, True, False) 239 240 def test_process_template_response_middleware_not_found(self): 241 pre_middleware = TestMiddleware() 242 middleware = TemplateResponseMiddleware() 243 post_middleware = TestMiddleware() 244 self._add_middleware(post_middleware) 245 self._add_middleware(middleware) 246 self._add_middleware(pre_middleware) 247 self.assert_exceptions_handled('/middleware_exceptions/not_found/', []) 248 249 # Check that the right middleware methods have been invoked 250 self.assert_middleware_usage(pre_middleware, True, True, False, True, True) 251 self.assert_middleware_usage(middleware, True, True, False, True, True) 252 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 207 253 208 254 def test_process_response_middleware_not_found(self): 209 255 pre_middleware = TestMiddleware() … … 215 261 self.assert_exceptions_handled('/middleware_exceptions/not_found/', []) 216 262 217 263 # Check that the right middleware methods have been invoked 218 self.assert_middleware_usage(pre_middleware, True, True, True, True)219 self.assert_middleware_usage(middleware, True, True, True, True)220 self.assert_middleware_usage(post_middleware, True, True, True, True)264 self.assert_middleware_usage(pre_middleware, True, True, False, True, True) 265 self.assert_middleware_usage(middleware, True, True, False, True, True) 266 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 221 267 222 268 def test_process_exception_middleware_not_found(self): 223 269 pre_middleware = TestMiddleware() … … 229 275 self.assert_exceptions_handled('/middleware_exceptions/not_found/', []) 230 276 231 277 # Check that the right middleware methods have been invoked 232 self.assert_middleware_usage(pre_middleware, True, True,True, False)233 self.assert_middleware_usage(middleware, True, True, True,True)234 self.assert_middleware_usage(post_middleware, True, True, True,True)278 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 279 self.assert_middleware_usage(middleware, True, True, False, True, True) 280 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 235 281 236 282 def test_process_request_middleware_exception(self): 237 283 pre_middleware = TestMiddleware() … … 243 289 self.assert_exceptions_handled('/middleware_exceptions/error/', []) 244 290 245 291 # Check that the right middleware methods have been invoked 246 self.assert_middleware_usage(pre_middleware, True,False, True, False)247 self.assert_middleware_usage(middleware, True,False, True, False)248 self.assert_middleware_usage(post_middleware, False, False, True, False)292 self.assert_middleware_usage(pre_middleware, True, False, False, True, False) 293 self.assert_middleware_usage(middleware, True, False, False, True, False) 294 self.assert_middleware_usage(post_middleware, False, False, False, True, False) 249 295 250 296 def test_process_view_middleware_exception(self): 251 297 pre_middleware = TestMiddleware() … … 257 303 self.assert_exceptions_handled('/middleware_exceptions/error/', []) 258 304 259 305 # Check that the right middleware methods have been invoked 260 self.assert_middleware_usage(pre_middleware, True, True, True, False)261 self.assert_middleware_usage(middleware, True, True, True, False)262 self.assert_middleware_usage(post_middleware, True, False, True, False)306 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 307 self.assert_middleware_usage(middleware, True, True, False, True, False) 308 self.assert_middleware_usage(post_middleware, True, False, False, True, False) 263 309 264 310 def test_process_response_middleware_exception(self): 265 311 pre_middleware = TestMiddleware() … … 271 317 self.assert_exceptions_handled('/middleware_exceptions/error/', ['Error in view'], Exception()) 272 318 273 319 # Check that the right middleware methods have been invoked 274 self.assert_middleware_usage(pre_middleware, True, True, True, True)275 self.assert_middleware_usage(middleware, True, True, True, True)276 self.assert_middleware_usage(post_middleware, True, True, True, True)320 self.assert_middleware_usage(pre_middleware, True, True, False, True, True) 321 self.assert_middleware_usage(middleware, True, True, False, True, True) 322 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 277 323 278 324 def test_process_exception_middleware_exception(self): 279 325 pre_middleware = TestMiddleware() … … 285 331 self.assert_exceptions_handled('/middleware_exceptions/error/', []) 286 332 287 333 # Check that the right middleware methods have been invoked 288 self.assert_middleware_usage(pre_middleware, True, True, True, False)289 self.assert_middleware_usage(middleware, True, True, True, True)290 self.assert_middleware_usage(post_middleware, True, True, True, True)334 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 335 self.assert_middleware_usage(middleware, True, True, False, True, True) 336 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 291 337 292 338 def test_process_request_middleware_null_view(self): 293 339 pre_middleware = TestMiddleware() … … 299 345 self.assert_exceptions_handled('/middleware_exceptions/null_view/', []) 300 346 301 347 # Check that the right middleware methods have been invoked 302 self.assert_middleware_usage(pre_middleware, True, False, True, False)303 self.assert_middleware_usage(middleware, True, False, True, False)304 self.assert_middleware_usage(post_middleware, False, False, True, False)348 self.assert_middleware_usage(pre_middleware, True, False, False, True, False) 349 self.assert_middleware_usage(middleware, True, False, False, True, False) 350 self.assert_middleware_usage(post_middleware, False, False, False, True, False) 305 351 306 352 def test_process_view_middleware_null_view(self): 307 353 pre_middleware = TestMiddleware() … … 313 359 self.assert_exceptions_handled('/middleware_exceptions/null_view/', []) 314 360 315 361 # Check that the right middleware methods have been invoked 316 self.assert_middleware_usage(pre_middleware, True, True,True, False)317 self.assert_middleware_usage(middleware, True, True,True, False)318 self.assert_middleware_usage(post_middleware, True, False, True, False)362 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 363 self.assert_middleware_usage(middleware, True, True, False, True, False) 364 self.assert_middleware_usage(post_middleware, True, False, False, True, False) 319 365 320 366 def test_process_response_middleware_null_view(self): 321 367 pre_middleware = TestMiddleware() … … 330 376 ValueError()) 331 377 332 378 # Check that the right middleware methods have been invoked 333 self.assert_middleware_usage(pre_middleware, True, True, True,False)334 self.assert_middleware_usage(middleware, True, True, True,False)335 self.assert_middleware_usage(post_middleware, True, True, True,False)379 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 380 self.assert_middleware_usage(middleware, True, True, False, True, False) 381 self.assert_middleware_usage(post_middleware, True, True, False, True, False) 336 382 337 383 def test_process_exception_middleware_null_view(self): 338 384 pre_middleware = TestMiddleware() … … 347 393 ValueError()) 348 394 349 395 # Check that the right middleware methods have been invoked 350 self.assert_middleware_usage(pre_middleware, True, True, True, False)351 self.assert_middleware_usage(middleware, True, True, True, False)352 self.assert_middleware_usage(post_middleware, True, True, True, False)396 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 397 self.assert_middleware_usage(middleware, True, True, False, True, False) 398 self.assert_middleware_usage(post_middleware, True, True, False, True, False) 353 399 354 400 def test_process_request_middleware_permission_denied(self): 355 401 pre_middleware = TestMiddleware() … … 361 407 self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', []) 362 408 363 409 # Check that the right middleware methods have been invoked 364 self.assert_middleware_usage(pre_middleware, True, False, True, False)365 self.assert_middleware_usage(middleware, True, False, True, False)366 self.assert_middleware_usage(post_middleware, False, False, True, False)410 self.assert_middleware_usage(pre_middleware, True, False, False, True, False) 411 self.assert_middleware_usage(middleware, True, False, False, True, False) 412 self.assert_middleware_usage(post_middleware, False, False, False, True, False) 367 413 368 414 def test_process_view_middleware_permission_denied(self): 369 415 pre_middleware = TestMiddleware() … … 375 421 self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', []) 376 422 377 423 # Check that the right middleware methods have been invoked 378 self.assert_middleware_usage(pre_middleware, True, True, True, False)379 self.assert_middleware_usage(middleware, True, True, True, False)380 self.assert_middleware_usage(post_middleware, True, False, True, False)424 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 425 self.assert_middleware_usage(middleware, True, True, False, True, False) 426 self.assert_middleware_usage(post_middleware, True, False, False, True, False) 381 427 382 428 def test_process_response_middleware_permission_denied(self): 383 429 pre_middleware = TestMiddleware() … … 389 435 self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', []) 390 436 391 437 # Check that the right middleware methods have been invoked 392 self.assert_middleware_usage(pre_middleware, True, True, True, True)393 self.assert_middleware_usage(middleware, True, True, True, True)394 self.assert_middleware_usage(post_middleware, True, True, True, True)438 self.assert_middleware_usage(pre_middleware, True, True, False, True, True) 439 self.assert_middleware_usage(middleware, True, True, False, True, True) 440 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 395 441 396 442 def test_process_exception_middleware_permission_denied(self): 397 443 pre_middleware = TestMiddleware() … … 403 449 self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', []) 404 450 405 451 # Check that the right middleware methods have been invoked 406 self.assert_middleware_usage(pre_middleware, True, True, True, False)407 self.assert_middleware_usage(middleware, True, True, True, True)408 self.assert_middleware_usage(post_middleware, True, True, True, True)452 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 453 self.assert_middleware_usage(middleware, True, True, False, True, True) 454 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 409 455 410 456 class BadMiddlewareTests(BaseMiddlewareExceptionTest): 411 457 … … 419 465 self.assert_exceptions_handled('/middleware_exceptions/view/', ['Test Request Exception']) 420 466 421 467 # Check that the right middleware methods have been invoked 422 self.assert_middleware_usage(pre_middleware, True, False, True, False)423 self.assert_middleware_usage(bad_middleware, True, False, True, False)424 self.assert_middleware_usage(post_middleware, False, False, True, False)468 self.assert_middleware_usage(pre_middleware, True, False, False, True, False) 469 self.assert_middleware_usage(bad_middleware, True, False, False, True, False) 470 self.assert_middleware_usage(post_middleware, False, False, False, True, False) 425 471 426 472 def test_process_view_bad_middleware(self): 427 473 pre_middleware = TestMiddleware() … … 433 479 self.assert_exceptions_handled('/middleware_exceptions/view/', ['Test View Exception']) 434 480 435 481 # Check that the right middleware methods have been invoked 436 self.assert_middleware_usage(pre_middleware, True, True, True, False) 437 self.assert_middleware_usage(bad_middleware, True, True, True, False) 438 self.assert_middleware_usage(post_middleware, True, False, True, False) 482 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 483 self.assert_middleware_usage(bad_middleware, True, True, False, True, False) 484 self.assert_middleware_usage(post_middleware, True, False, False, True, False) 485 486 def test_process_template_response_bad_middleware(self): 487 pre_middleware = TestMiddleware() 488 bad_middleware = BadTemplateResponseMiddleware() 489 post_middleware = TestMiddleware() 490 self._add_middleware(post_middleware) 491 self._add_middleware(bad_middleware) 492 self._add_middleware(pre_middleware) 493 self.assert_exceptions_handled('/middleware_exceptions/template_response/', ['Test Template Response Exception']) 494 495 # Check that the right middleware methods have been invoked 496 self.assert_middleware_usage(pre_middleware, True, True, False, False, False) 497 self.assert_middleware_usage(bad_middleware, True, True, True, False, False) 498 self.assert_middleware_usage(post_middleware, True, True, True, False, False) 439 499 440 500 def test_process_response_bad_middleware(self): 441 501 pre_middleware = TestMiddleware() … … 447 507 self.assert_exceptions_handled('/middleware_exceptions/view/', ['Test Response Exception']) 448 508 449 509 # Check that the right middleware methods have been invoked 450 self.assert_middleware_usage(pre_middleware, True, True, False, False)451 self.assert_middleware_usage(bad_middleware, True, True, True, False)452 self.assert_middleware_usage(post_middleware, True, True, True, False)510 self.assert_middleware_usage(pre_middleware, True, True, False, False, False) 511 self.assert_middleware_usage(bad_middleware, True, True, False, True, False) 512 self.assert_middleware_usage(post_middleware, True, True, False, True, False) 453 513 454 514 def test_process_exception_bad_middleware(self): 455 515 pre_middleware = TestMiddleware() … … 461 521 self.assert_exceptions_handled('/middleware_exceptions/view/', []) 462 522 463 523 # Check that the right middleware methods have been invoked 464 self.assert_middleware_usage(pre_middleware, True, True, True, False)465 self.assert_middleware_usage(bad_middleware, True, True, True, False)466 self.assert_middleware_usage(post_middleware, True, True, True, False)524 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 525 self.assert_middleware_usage(bad_middleware, True, True, False, True, False) 526 self.assert_middleware_usage(post_middleware, True, True, False, True, False) 467 527 468 528 def test_process_request_bad_middleware_not_found(self): 469 529 pre_middleware = TestMiddleware() … … 475 535 self.assert_exceptions_handled('/middleware_exceptions/not_found/', ['Test Request Exception']) 476 536 477 537 # Check that the right middleware methods have been invoked 478 self.assert_middleware_usage(pre_middleware, True, False, True, False)479 self.assert_middleware_usage(bad_middleware, True, False, True, False)480 self.assert_middleware_usage(post_middleware, False, False, True, False)538 self.assert_middleware_usage(pre_middleware, True, False, False, True, False) 539 self.assert_middleware_usage(bad_middleware, True, False, False, True, False) 540 self.assert_middleware_usage(post_middleware, False, False, False, True, False) 481 541 482 542 def test_process_view_bad_middleware_not_found(self): 483 543 pre_middleware = TestMiddleware() … … 489 549 self.assert_exceptions_handled('/middleware_exceptions/not_found/', ['Test View Exception']) 490 550 491 551 # Check that the right middleware methods have been invoked 492 self.assert_middleware_usage(pre_middleware, True, True, True, False)493 self.assert_middleware_usage(bad_middleware, True, True, True, False)494 self.assert_middleware_usage(post_middleware, True, False, True, False)552 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 553 self.assert_middleware_usage(bad_middleware, True, True, False, True, False) 554 self.assert_middleware_usage(post_middleware, True, False, False, True, False) 495 555 496 556 def test_process_response_bad_middleware_not_found(self): 497 557 pre_middleware = TestMiddleware() … … 503 563 self.assert_exceptions_handled('/middleware_exceptions/not_found/', ['Test Response Exception']) 504 564 505 565 # Check that the right middleware methods have been invoked 506 self.assert_middleware_usage(pre_middleware, True, True, False, True)507 self.assert_middleware_usage(bad_middleware, True, True, True, True)508 self.assert_middleware_usage(post_middleware, True, True, True, True)566 self.assert_middleware_usage(pre_middleware, True, True, False, False, True) 567 self.assert_middleware_usage(bad_middleware, True, True, False, True, True) 568 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 509 569 510 570 def test_process_exception_bad_middleware_not_found(self): 511 571 pre_middleware = TestMiddleware() … … 517 577 self.assert_exceptions_handled('/middleware_exceptions/not_found/', ['Test Exception Exception']) 518 578 519 579 # Check that the right middleware methods have been invoked 520 self.assert_middleware_usage(pre_middleware, True, True, True, False)521 self.assert_middleware_usage(bad_middleware, True, True, True, True)522 self.assert_middleware_usage(post_middleware, True, True, True, True)580 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 581 self.assert_middleware_usage(bad_middleware, True, True, False, True, True) 582 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 523 583 524 584 def test_process_request_bad_middleware_exception(self): 525 585 pre_middleware = TestMiddleware() … … 531 591 self.assert_exceptions_handled('/middleware_exceptions/error/', ['Test Request Exception']) 532 592 533 593 # Check that the right middleware methods have been invoked 534 self.assert_middleware_usage(pre_middleware, True, False, True, False)535 self.assert_middleware_usage(bad_middleware, True, False, True, False)536 self.assert_middleware_usage(post_middleware, False, False, True, False)594 self.assert_middleware_usage(pre_middleware, True, False, False, True, False) 595 self.assert_middleware_usage(bad_middleware, True, False, False, True, False) 596 self.assert_middleware_usage(post_middleware, False, False, False, True, False) 537 597 538 598 def test_process_view_bad_middleware_exception(self): 539 599 pre_middleware = TestMiddleware() … … 545 605 self.assert_exceptions_handled('/middleware_exceptions/error/', ['Test View Exception']) 546 606 547 607 # Check that the right middleware methods have been invoked 548 self.assert_middleware_usage(pre_middleware, True, True, True, False)549 self.assert_middleware_usage(bad_middleware, True, True, True, False)550 self.assert_middleware_usage(post_middleware, True, False, True, False)608 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 609 self.assert_middleware_usage(bad_middleware, True, True, False, True, False) 610 self.assert_middleware_usage(post_middleware, True, False, False, True, False) 551 611 552 612 def test_process_response_bad_middleware_exception(self): 553 613 pre_middleware = TestMiddleware() … … 559 619 self.assert_exceptions_handled('/middleware_exceptions/error/', ['Error in view', 'Test Response Exception']) 560 620 561 621 # Check that the right middleware methods have been invoked 562 self.assert_middleware_usage(pre_middleware, True, True, False, True)563 self.assert_middleware_usage(bad_middleware, True, True, True, True)564 self.assert_middleware_usage(post_middleware, True, True, True, True)622 self.assert_middleware_usage(pre_middleware, True, True, False, False, True) 623 self.assert_middleware_usage(bad_middleware, True, True, False, True, True) 624 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 565 625 566 626 def test_process_exception_bad_middleware_exception(self): 567 627 pre_middleware = TestMiddleware() … … 573 633 self.assert_exceptions_handled('/middleware_exceptions/error/', ['Test Exception Exception']) 574 634 575 635 # Check that the right middleware methods have been invoked 576 self.assert_middleware_usage(pre_middleware, True, True, True, False)577 self.assert_middleware_usage(bad_middleware, True, True, True, True)578 self.assert_middleware_usage(post_middleware, True, True, True, True)636 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 637 self.assert_middleware_usage(bad_middleware, True, True, False, True, True) 638 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 579 639 580 640 def test_process_request_bad_middleware_null_view(self): 581 641 pre_middleware = TestMiddleware() … … 587 647 self.assert_exceptions_handled('/middleware_exceptions/null_view/', ['Test Request Exception']) 588 648 589 649 # Check that the right middleware methods have been invoked 590 self.assert_middleware_usage(pre_middleware, True, False, True, False)591 self.assert_middleware_usage(bad_middleware, True, False, True, False)592 self.assert_middleware_usage(post_middleware, False, False, True, False)650 self.assert_middleware_usage(pre_middleware, True, False, False, True, False) 651 self.assert_middleware_usage(bad_middleware, True, False, False, True, False) 652 self.assert_middleware_usage(post_middleware, False, False, False, True, False) 593 653 594 654 def test_process_view_bad_middleware_null_view(self): 595 655 pre_middleware = TestMiddleware() … … 601 661 self.assert_exceptions_handled('/middleware_exceptions/null_view/', ['Test View Exception']) 602 662 603 663 # Check that the right middleware methods have been invoked 604 self.assert_middleware_usage(pre_middleware, True, True, True, False)605 self.assert_middleware_usage(bad_middleware, True, True, True, False)606 self.assert_middleware_usage(post_middleware, True, False, True, False)664 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 665 self.assert_middleware_usage(bad_middleware, True, True, False, True, False) 666 self.assert_middleware_usage(post_middleware, True, False, False, True, False) 607 667 608 668 def test_process_response_bad_middleware_null_view(self): 609 669 pre_middleware = TestMiddleware() … … 618 678 ]) 619 679 620 680 # Check that the right middleware methods have been invoked 621 self.assert_middleware_usage(pre_middleware, True, True, False, False)622 self.assert_middleware_usage(bad_middleware, True, True, True, False)623 self.assert_middleware_usage(post_middleware, True, True, True, False)681 self.assert_middleware_usage(pre_middleware, True, True, False, False, False) 682 self.assert_middleware_usage(bad_middleware, True, True, False, True, False) 683 self.assert_middleware_usage(post_middleware, True, True, False, True, False) 624 684 625 685 def test_process_exception_bad_middleware_null_view(self): 626 686 pre_middleware = TestMiddleware() … … 635 695 ValueError()) 636 696 637 697 # Check that the right middleware methods have been invoked 638 self.assert_middleware_usage(pre_middleware, True, True, True, False)639 self.assert_middleware_usage(bad_middleware, True, True, True, False)640 self.assert_middleware_usage(post_middleware, True, True, True, False)698 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 699 self.assert_middleware_usage(bad_middleware, True, True, False, True, False) 700 self.assert_middleware_usage(post_middleware, True, True, False, True, False) 641 701 642 702 def test_process_request_bad_middleware_permission_denied(self): 643 703 pre_middleware = TestMiddleware() … … 649 709 self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', ['Test Request Exception']) 650 710 651 711 # Check that the right middleware methods have been invoked 652 self.assert_middleware_usage(pre_middleware, True, False, True, False)653 self.assert_middleware_usage(bad_middleware, True, False, True, False)654 self.assert_middleware_usage(post_middleware, False, False, True, False)712 self.assert_middleware_usage(pre_middleware, True, False, False, True, False) 713 self.assert_middleware_usage(bad_middleware, True, False, False, True, False) 714 self.assert_middleware_usage(post_middleware, False, False, False, True, False) 655 715 656 716 def test_process_view_bad_middleware_permission_denied(self): 657 717 pre_middleware = TestMiddleware() … … 663 723 self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', ['Test View Exception']) 664 724 665 725 # Check that the right middleware methods have been invoked 666 self.assert_middleware_usage(pre_middleware, True, True, True, False)667 self.assert_middleware_usage(bad_middleware, True, True, True, False)668 self.assert_middleware_usage(post_middleware, True, False, True, False)726 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 727 self.assert_middleware_usage(bad_middleware, True, True, False, True, False) 728 self.assert_middleware_usage(post_middleware, True, False, False, True, False) 669 729 670 730 def test_process_response_bad_middleware_permission_denied(self): 671 731 pre_middleware = TestMiddleware() … … 677 737 self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', ['Test Response Exception']) 678 738 679 739 # Check that the right middleware methods have been invoked 680 self.assert_middleware_usage(pre_middleware, True, True, False, True)681 self.assert_middleware_usage(bad_middleware, True, True, True, True)682 self.assert_middleware_usage(post_middleware, True, True, True, True)740 self.assert_middleware_usage(pre_middleware, True, True, False, False, True) 741 self.assert_middleware_usage(bad_middleware, True, True, False, True, True) 742 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 683 743 684 744 def test_process_exception_bad_middleware_permission_denied(self): 685 745 pre_middleware = TestMiddleware() … … 691 751 self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', ['Test Exception Exception']) 692 752 693 753 # Check that the right middleware methods have been invoked 694 self.assert_middleware_usage(pre_middleware, True, True, True, False)695 self.assert_middleware_usage(bad_middleware, True, True, True, True)696 self.assert_middleware_usage(post_middleware, True, True, True, True)754 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 755 self.assert_middleware_usage(bad_middleware, True, True, False, True, True) 756 self.assert_middleware_usage(post_middleware, True, True, False, True, True) -
tests/regressiontests/middleware_exceptions/urls.py
diff -r 8343c0d86151 tests/regressiontests/middleware_exceptions/urls.py
a b 9 9 (r'^error/$', views.server_error), 10 10 (r'^null_view/$', views.null_view), 11 11 (r'^permission_denied/$', views.permission_denied), 12 13 (r'^template_response/$', views.template_response), 14 (r'^template_response_error/$', views.template_response_error), 12 15 ) -
tests/regressiontests/middleware_exceptions/views.py
diff -r 8343c0d86151 tests/regressiontests/middleware_exceptions/views.py
a b 1 1 from django import http 2 2 from django.core.exceptions import PermissionDenied 3 from django.shortcuts import render 4 from django.template import Template 3 5 4 6 def normal_view(request): 5 7 return http.HttpResponse('OK') 6 8 9 def template_response(request): 10 return render(request, Template('OK')) 11 12 def template_response_error(request): 13 return render(request, Template('{%')) 14 7 15 def not_found(request): 8 16 raise http.Http404() 9 17 -
new file tests/regressiontests/templates/response.py
diff -r 8343c0d86151 tests/regressiontests/templates/response.py
- + 1 import os 2 from django.utils import unittest 3 from django.test import RequestFactory 4 from django.conf import settings 5 import django.template.context 6 from django.template import Template, Context, RequestContext 7 from django.template.response import (TemplateResponse, SimpleTemplateResponse, 8 ContentNotReadyError) 9 10 def test_processor(request): 11 return {'processors': 'yes'} 12 test_processor_name = 'regressiontests.templates.response.test_processor' 13 14 class BaseTemplateResponseTest(unittest.TestCase): 15 # tests rely on fact that global context 16 # processors should only work when RequestContext is used. 17 18 def setUp(self): 19 self.factory = RequestFactory() 20 self._old_processors = settings.TEMPLATE_CONTEXT_PROCESSORS 21 self._old_TEMPLATE_DIRS = settings.TEMPLATE_DIRS 22 settings.TEMPLATE_CONTEXT_PROCESSORS = [test_processor_name] 23 settings.TEMPLATE_DIRS = ( 24 os.path.join( 25 os.path.dirname(__file__), 26 'templates' 27 ), 28 ) 29 # Force re-evaluation of the contex processor list 30 django.template.context._standard_context_processors = None 31 32 def tearDown(self): 33 settings.TEMPLATE_DIRS = self._old_TEMPLATE_DIRS 34 settings.TEMPLATE_CONTEXT_PROCESSORS = self._old_processors 35 # Force re-evaluation of the contex processor list 36 django.template.context._standard_context_processors = None 37 38 39 class SimpleTemplateResponseTest(BaseTemplateResponseTest): 40 41 def _response(self, template='foo', *args, **kwargs): 42 return SimpleTemplateResponse(Template(template), *args, **kwargs) 43 44 def test_template_resolving(self): 45 response = SimpleTemplateResponse('first/test.html') 46 response.bake() 47 self.assertEqual('First template\n', response.content) 48 49 templates = ['foo.html', 'second/test.html', 'first/test.html'] 50 response = SimpleTemplateResponse(templates) 51 response.bake() 52 self.assertEqual('Second template\n', response.content) 53 54 response = self._response() 55 response.bake() 56 self.assertEqual(response.content, 'foo') 57 58 def test_explicit_baking(self): 59 # explicit baking 60 response = self._response() 61 self.assertFalse(response.baked) 62 response.bake() 63 self.assertTrue(response.baked) 64 65 def test_bake(self): 66 # response is not re-baked without the bake call 67 response = self._response().bake() 68 self.assertEqual(response.content, 'foo') 69 70 response.template_name = Template('bar{{ baz }}') 71 self.assertEqual(response.content, 'foo') 72 response.bake() 73 self.assertEqual(response.content, 'bar') 74 75 response.template_context = {'baz': 'baz'} 76 self.assertEqual(response.content, 'bar') 77 response.bake() 78 self.assertEqual(response.content, 'barbaz') 79 80 response.template_context = {'baz': 'spam'} 81 for x in response: 82 pass 83 self.assertEqual(response.content, 'barbaz') 84 85 def test_iteration_unbaked(self): 86 # unbaked response raises an exception on iteration 87 response = self._response() 88 self.assertFalse(response.baked) 89 90 def iteration(): 91 for x in response: 92 pass 93 self.assertRaises(ContentNotReadyError, iteration) 94 self.assertFalse(response.baked) 95 96 def test_iteration_baked(self): 97 # iteration works for baked responses 98 response = self._response().bake() 99 res = [x for x in response] 100 self.assertEqual(res, ['foo']) 101 102 def test_content_access_unbaked(self): 103 # unbaked response raises an exception when content is accessed 104 response = self._response() 105 self.assertFalse(response.baked) 106 self.assertRaises(ContentNotReadyError, lambda: response.content) 107 self.assertFalse(response.baked) 108 109 def test_content_access_baked(self): 110 # baked response content can be accessed 111 response = self._response().bake() 112 self.assertEqual(response.content, 'foo') 113 114 def test_set_content(self): 115 # content can be overriden 116 response = self._response() 117 self.assertFalse(response.baked) 118 response.content = 'spam' 119 self.assertTrue(response.baked) 120 self.assertEqual(response.content, 'spam') 121 response.content = 'baz' 122 self.assertEqual(response.content, 'baz') 123 124 def test_dict_context(self): 125 response = self._response('{{ foo }}{{ processors }}', 126 {'foo': 'bar'}) 127 self.assertEqual(response.template_context, {'foo': 'bar'}) 128 response.bake() 129 self.assertEqual(response.content, 'bar') 130 131 def test_context_instance(self): 132 response = self._response('{{ foo }}{{ processors }}', 133 Context({'foo': 'bar'})) 134 self.assertEqual(response.template_context.__class__, Context) 135 response.bake() 136 self.assertEqual(response.content, 'bar') 137 138 def test_kwargs(self): 139 response = self._response(content_type = 'application/json', status=504) 140 self.assertEqual(response['content-type'], 'application/json') 141 self.assertEqual(response.status_code, 504) 142 143 def test_args(self): 144 response = SimpleTemplateResponse('', {}, 'application/json', 504) 145 self.assertEqual(response['content-type'], 'application/json') 146 self.assertEqual(response.status_code, 504) 147 148 149 class TemplateResponseTest(BaseTemplateResponseTest): 150 151 def _response(self, template='foo', *args, **kwargs): 152 return TemplateResponse(self.factory.get('/'), Template(template), 153 *args, **kwargs) 154 155 def test_render(self): 156 response = self._response('{{ foo }}{{ processors }}').bake() 157 self.assertEqual(response.content, 'yes') 158 159 def test_render_with_requestcontext(self): 160 response = self._response('{{ foo }}{{ processors }}', 161 {'foo': 'bar'}).bake() 162 self.assertEqual(response.content, 'baryes') 163 164 def test_render_with_context(self): 165 response = self._response('{{ foo }}{{ processors }}', 166 Context({'foo': 'bar'})).bake() 167 self.assertEqual(response.content, 'bar') 168 169 def test_kwargs(self): 170 response = self._response(content_type = 'application/json', 171 status=504) 172 self.assertEqual(response['content-type'], 'application/json') 173 self.assertEqual(response.status_code, 504) 174 175 def test_args(self): 176 response = TemplateResponse(self.factory.get('/'), '', {}, 177 'application/json', 504) 178 self.assertEqual(response['content-type'], 'application/json') 179 self.assertEqual(response.status_code, 504) -
tests/regressiontests/templates/tests.py
diff -r 8343c0d86151 tests/regressiontests/templates/tests.py
a b 27 27 from unicode import unicode_tests 28 28 from nodelist import NodelistTest 29 29 from smartif import * 30 from response import * 30 31 31 32 try: 32 33 from loaders import * -
new file tests/regressiontests/views/templates/debug/render_test.html
diff -r 8343c0d86151 tests/regressiontests/views/templates/debug/render_test.html
- + 1 {{ foo }}.{{ bar }}.{{ baz }}.{{ processors }} -
tests/regressiontests/views/tests/__init__.py
diff -r 8343c0d86151 tests/regressiontests/views/tests/__init__.py
a b 7 7 from i18n import * 8 8 from specials import * 9 9 from static import * 10 from shortcuts import * -
new file tests/regressiontests/views/tests/shortcuts.py
diff -r 8343c0d86151 tests/regressiontests/views/tests/shortcuts.py
- + 1 from django.test import RequestFactory 2 from django.template import Template 3 from django.shortcuts import render 4 5 from regressiontests.templates.response import BaseTemplateResponseTest 6 7 def library_view(request): 8 return render(request, 'debug/render_test.html', 9 {'foo': 'foo', 'baz': 'baz'}) 10 11 def customized_context_view(request): 12 response = library_view(request) 13 response.template_context.update({'bar': 'bar', 'baz': 'spam'}) 14 return response 15 16 def customized_template_view(request): 17 response = library_view(request) 18 response.template_name = Template('context does not matter') 19 return response 20 21 22 class RenderTest(BaseTemplateResponseTest): 23 24 def setUp(self): 25 super(RenderTest, self).setUp() 26 self.request = self.factory.get('/') 27 28 def test_library_view(self): 29 response = library_view(self.request).bake() 30 self.assertEqual(response.content, 'foo..baz.yes\n') 31 32 def test_customized_context(self): 33 response = customized_context_view(self.request).bake() 34 self.assertEqual(response.content, 'foo.bar.spam.yes\n') 35 36 def test_customized_template(self): 37 response = customized_template_view(self.request).bake() 38 self.assertEqual(response.content, 'context does not matter') 39 40 def test_status_and_content_type(self): 41 response = render(self.request, 'base.html', {'foo': 'bar'}, 42 'application/json', 504) 43 self.assertEqual(response.status_code, 504) 44 self.assertEqual(response['content-type'], 'application/json') 45