Ticket #12816: t12815-rc1.diff
File t12815-rc1.diff, 81.2 KB (added by , 14 years ago) |
---|
-
django/contrib/messages/middleware.py
diff -r 78ad3faa689b 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 78ad3faa689b django/contrib/messages/tests/base.py
a b 103 103 storage = self.get_storage() 104 104 self.assertFalse(storage.added_new) 105 105 storage.add(constants.INFO, 'Test message 1') 106 self.assert _(storage.added_new)106 self.assertTrue(storage.added_new) 107 107 storage.add(constants.INFO, 'Test message 2', extra_tags='tag') 108 108 self.assertEqual(len(storage), 2) 109 109 … … 180 180 for msg in data['messages']: 181 181 self.assertContains(response, msg) 182 182 183 def test_with_template_response(self): 184 settings.MESSAGE_LEVEL = constants.DEBUG 185 data = { 186 'messages': ['Test message %d' % x for x in xrange(10)], 187 } 188 show_url = reverse('django.contrib.messages.tests.urls.show_template_response') 189 for level in self.levels.keys(): 190 add_url = reverse('django.contrib.messages.tests.urls.add_template_response', 191 args=(level,)) 192 response = self.client.post(add_url, data, follow=True) 193 self.assertRedirects(response, show_url) 194 self.assertTrue('messages' in response.context) 195 for msg in data['messages']: 196 self.assertContains(response, msg) 197 198 # there shouldn't be any messages on second GET request 199 response = self.client.get(show_url) 200 for msg in data['messages']: 201 self.assertNotContains(response, msg) 202 183 203 def test_multiple_posts(self): 184 204 """ 185 205 Tests that messages persist properly when multiple POSTs are made -
django/contrib/messages/tests/urls.py
diff -r 78ad3faa689b 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 38 show_url = reverse('django.contrib.messages.tests.urls.show_template_response') 39 return HttpResponseRedirect(show_url) 22 40 23 41 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 %}""") 42 t = Template(TEMPLATE) 33 43 return HttpResponse(t.render(RequestContext(request))) 34 44 45 def show_template_response(request): 46 return TemplateResponse(request, Template(TEMPLATE)) 35 47 36 48 urlpatterns = patterns('', 37 49 ('^add/(debug|info|success|warning|error)/$', add), 38 50 ('^show/$', show), 51 ('^template_response/add/(debug|info|success|warning|error)/$', add_template_response), 52 ('^template_response/show/$', show_template_response), 39 53 ) -
django/core/handlers/base.py
diff -r 78ad3faa689b 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'): … … 164 154 urlresolvers.set_urlconf(None) 165 155 166 156 try: 157 # Apply template response middleware and the bake the response 158 # if the response can be baked 159 if hasattr(response, 'bake') and callable(response.bake): 160 for middleware_method in self._template_response_middleware: 161 response = middleware_method(request, response) 162 response.bake() 163 167 164 # Apply response middleware, regardless of the response 168 165 for middleware_method in self._response_middleware: 169 166 response = middleware_method(request, response) … … 241 238 if script_url: 242 239 return force_unicode(script_url[:-len(environ.get('PATH_INFO', ''))]) 243 240 return force_unicode(environ.get('SCRIPT_NAME', u'')) 241 242 def get_middleware_instance(middleware_path): 243 """ 244 Returns middleware instance 245 """ 246 try: 247 mw_module, mw_classname = middleware_path.rsplit('.', 1) 248 except ValueError: 249 raise exceptions.ImproperlyConfigured('%s isn\'t a middleware module' % middleware_path) 250 try: 251 mod = import_module(mw_module) 252 except ImportError, e: 253 raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e)) 254 try: 255 mw_class = getattr(mod, mw_classname) 256 except AttributeError: 257 raise exceptions.ImproperlyConfigured('Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname)) 258 259 return mw_class() -
django/shortcuts/__init__.py
diff -r 78ad3faa689b django/shortcuts/__init__.py
a b 4 4 for convenience's sake. 5 5 """ 6 6 7 from django.template import loader 7 from django.template import loader, RequestContext 8 8 from django.http import HttpResponse, Http404 9 9 from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect 10 10 from django.db.models.manager import Manager … … 19 19 httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)} 20 20 return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) 21 21 22 def render(request, *args, **kwargs): 23 """ 24 Returns a HttpResponse whose content is filled with the result of calling 25 django.template.loader.render_to_string() with the passed arguments. 26 Uses a RequestContext by default. 27 """ 28 httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)} 29 kwargs['context_instance'] = kwargs.get('context_instance', RequestContext(request)) 30 return HttpResponse(loader.render_to_string(*args, **kwargs), 31 **httpresponse_kwargs) 32 22 33 def redirect(to, *args, **kwargs): 23 34 """ 24 35 Returns an HttpResponseRedirect to the apropriate URL for the arguments 25 36 passed. 26 37 27 38 The arguments could be: 28 39 29 40 * A model: the model's `get_absolute_url()` function will be called. 30 41 31 42 * A view name, possibly with arguments: `urlresolvers.reverse()` will 32 43 be used to reverse-resolve the name. 33 44 34 45 * A URL, which will be used as-is for the redirect location. 35 46 36 47 By default issues a temporary redirect; pass permanent=True to issue a 37 48 permanent redirect 38 49 """ … … 40 51 redirect_class = HttpResponsePermanentRedirect 41 52 else: 42 53 redirect_class = HttpResponseRedirect 43 54 44 55 # If it's a model, use get_absolute_url() 45 56 if hasattr(to, 'get_absolute_url'): 46 57 return redirect_class(to.get_absolute_url()) 47 58 48 59 # Next try a reverse URL resolution. 49 60 try: 50 61 return redirect_class(urlresolvers.reverse(to, args=args, kwargs=kwargs)) … … 55 66 # If this doesn't "feel" like a URL, re-raise. 56 67 if '/' not in to and '.' not in to: 57 68 raise 58 69 59 70 # Finally, fall back and assume it's a URL 60 71 return redirect_class(to) 61 72 … … 101 112 obj_list = list(queryset.filter(*args, **kwargs)) 102 113 if not obj_list: 103 114 raise Http404('No %s matches the given query.' % queryset.model._meta.object_name) 104 return obj_list 105 No newline at end of file 115 return obj_list 116 -
new file django/template/response.py
diff -r 78ad3faa689b django/template/response.py
- + 1 from django.http import HttpResponse 2 from django.template import loader, Context, RequestContext 3 4 class ContentNotBakedError(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 # It would seem obvious to call these next two members 'template' and 12 # 'context', but those names are reserved as part of the test Client API. 13 # To avoid the name collision, we use 14 # tricky-to-debug problems 15 self.template_name = template 16 self.context_data = context 17 18 # _baked tracks whether the template and context has been baked into 19 # a final response. 20 self._baked = False 21 22 # content argument doesn't make sense here because it will be replaced 23 # with rendered template so we always pass empty string in order to 24 # prevent errors and provide shorter signature. 25 super(SimpleTemplateResponse, self).__init__('', mimetype, status, 26 content_type) 27 28 def resolve_template(self, template): 29 "Accepts a template object, path-to-template or list of paths" 30 if isinstance(template, (list, tuple)): 31 return loader.select_template(template) 32 elif isinstance(template, basestring): 33 return loader.get_template(template) 34 else: 35 return template 36 37 def resolve_context(self, context): 38 """Convert context data into a full Context object 39 (assuming it isn't already a Context object). 40 """ 41 if isinstance(context, Context): 42 return context 43 else: 44 return Context(context) 45 46 def render(self): 47 "Render the content of the response. Returns the rendered content" 48 template = self.resolve_template(self.template_name) 49 context = self.resolve_context(self.context_data) 50 content = template.render(context) 51 return content 52 53 def bake(self): 54 """Bake the response. 55 56 If the content has already been baked, this is a no-op. 57 58 Returns the baked response instance. 59 """ 60 if not self._baked: 61 self._set_content(self.render()) 62 return self 63 64 baked = property(lambda self: self._baked) 65 66 def __iter__(self): 67 if not self._baked: 68 raise ContentNotBakedError('The response content must be baked before it can be iterated over.') 69 return super(SimpleTemplateResponse, self).__iter__() 70 71 def _get_content(self): 72 if not self._baked: 73 raise ContentNotBakedError('The response content must be baked before it can be accessed.') 74 return super(SimpleTemplateResponse, self)._get_content() 75 76 def _set_content(self, value): 77 "Overrides rendered content, unless you later call bake()" 78 super(SimpleTemplateResponse, self)._set_content(value) 79 self._baked = True 80 81 content = property(_get_content, _set_content) 82 83 class TemplateResponse(SimpleTemplateResponse): 84 85 def __init__(self, request, template, context=None, mimetype=None, 86 status=None, content_type=None): 87 # self.request gets over-written by django.test.client.Client - and 88 # unlike context_data and template_name the _request should not 89 # be considered part of the public API. 90 self._request = request 91 super(TemplateResponse, self).__init__( 92 template, context, mimetype, status, content_type) 93 94 def resolve_context(self, context): 95 """Convert context data into a full RequestContext object 96 (assuming it isn't already a Context object). 97 """ 98 if isinstance(context, Context): 99 return context 100 else: 101 return RequestContext(self._request, context) 102 103 def bake(response): 104 """ 105 Bakes response if it can be baked. Unbakeable instances (such as 106 normal HttpResponse instances) are unaffected. 107 """ 108 if (hasattr(response, 'bake') and callable(response.bake)): 109 response.bake() -
django/views/generic/base.py
diff -r 78ad3faa689b django/views/generic/base.py
a b 1 1 from django import http 2 2 from django.core.exceptions import ImproperlyConfigured 3 3 from django.template import RequestContext, loader 4 from django.template.response import TemplateResponse 4 5 from django.utils.functional import update_wrapper 5 6 from django.utils.log import getLogger 6 7 from django.utils.decorators import classonlymethod … … 81 82 A mixin that can be used to render a template. 82 83 """ 83 84 template_name = None 85 response_class = TemplateResponse 84 86 85 def render_to_response(self, context ):87 def render_to_response(self, context, **response_kwargs): 86 88 """ 87 89 Returns a response with a template rendered with the given context. 88 90 """ 89 return self.get_response(self.render_template(context)) 90 91 def get_response(self, content, **httpresponse_kwargs): 92 """ 93 Construct an `HttpResponse` object. 94 """ 95 return http.HttpResponse(content, **httpresponse_kwargs) 96 97 def render_template(self, context): 98 """ 99 Render the template with a given context. 100 """ 101 context_instance = self.get_context_instance(context) 102 return self.get_template().render(context_instance) 103 104 def get_context_instance(self, context): 105 """ 106 Get the template context instance. Must return a Context (or subclass) 107 instance. 108 """ 109 return RequestContext(self.request, context) 110 111 def get_template(self): 112 """ 113 Get a ``Template`` object for the given request. 114 """ 115 names = self.get_template_names() 116 if not names: 117 raise ImproperlyConfigured(u"'%s' must provide template_name." 118 % self.__class__.__name__) 119 return self.load_template(names) 91 return self.response_class( 92 request = self.request, 93 template = self.get_template_names(), 94 context = context, 95 **response_kwargs 96 ) 120 97 121 98 def get_template_names(self): 122 99 """ 123 Return a list of template names to be used for the request. Must return124 a list. May not be called if get_template is overridden.100 Returns a list of template names to be used for the request. Must return 101 a list. May not be called if render_to_response is overridden. 125 102 """ 126 103 if self.template_name is None: 127 104 return [] 128 105 else: 129 106 return [self.template_name] 130 107 131 def load_template(self, names):132 """133 Load a list of templates using the default template loader.134 """135 return loader.select_template(names)136 137 108 138 109 class TemplateView(TemplateResponseMixin, View): 139 110 """ -
docs/index.txt
diff -r 78ad3faa689b 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 objects <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 78ad3faa689b 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:: 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 78ad3faa689b 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 -
new file docs/ref/template-response.txt
diff -r 78ad3faa689b 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 Standard HttpResponse objects are static structures. They are provided 11 with a block of pre-rendered content at time of construction, and 12 while that content can be modified, it isn't in a form that makes it 13 easy to perform modifications. 14 15 However, it can sometimes be beneficial to allow decorators or 16 middleware to modify a response *after* it has been constructed by the 17 view. For example, you may want to change the template that is used, 18 or put additional data into the context. 19 20 TemplateResponse provides a way to do just that. Unlike basic 21 HttpResponse objects, TemplateResponse objects retain the details of 22 the template and context that was provided by the view to compute the 23 response. The final output of the response is not computed until 24 it is needed. 25 26 TemplateResponse objects 27 ======================== 28 29 .. class:: SimpleTemplateResponse() 30 31 Attributes 32 ---------- 33 34 .. attribute:: SimpleTemplateResponse.template_name 35 36 The name of the template to be rendered. Accepts 37 :class:`django.template.Template` object, path to template or list 38 of paths. 39 40 Example: ``['foo.html', 'path/to/bar.html']`` 41 42 .. attribute:: SimpleTemplateResponse.context_data 43 44 The context data to be used when rendering the template. It can be 45 a dictionary or a context object. 46 47 Example: ``{'foo': 123}`` 48 49 50 Methods 51 ------- 52 53 .. method:: SimpleTemplateResponse.__init__(template, context=None, mimetype=None, status=None, content_type=None) 54 55 Instantiates an 56 :class:`~django.template.response.SimpleTemplateResponse` object 57 with the given template, context, MIME type and HTTP status. 58 59 ``template`` is a full name of a template, or a sequence of 60 template names. :class:`django.template.Template` instances can also be used. 61 62 ``context`` is a dictionary of values to add to the template context. 63 By default, this is an empty dictionary. :class:`~django.template.Context` objects are also 64 accepted as ``context`` values. 65 66 ``status`` is the HTTP Status code for the response. 67 68 ``content_type`` is an alias for ``mimetype``. Historically, this parameter 69 was only called ``mimetype``, but since this is actually the value included 70 in the HTTP ``Content-Type`` header, it can also include the character set 71 encoding, which makes it more than just a MIME type specification. 72 If ``mimetype`` is specified (not ``None``), that value is used. 73 Otherwise, ``content_type`` is used. If neither is given, the 74 ``DEFAULT_CONTENT_TYPE`` setting is used. 75 76 77 .. method:: SimpleTemplateResponse.resolve_context(context) 78 79 Converts context data into a context instance that can be used for 80 rendering a template. Accepts a dictionary of context data or a 81 context object. Returns a :class:`~django.template.Context` 82 instance containing the provided data. 83 84 Override this method in order to customize context instantiation. 85 86 .. method:: SimpleTemplateResponse.resolve_template(template) 87 88 Resolves the template instance to use for rendering. Accepts a 89 path of a template to use, or a sequence of template paths. 90 :class:`~django.template.Template` instances may also be provided. 91 Returns the :class:`~django.template.Template` instance to be 92 rendered. 93 94 Override this method in order to customize template rendering. 95 96 .. method:: SimpleTemplateResponse.render(): 97 98 Renders a template instance returned by 99 :meth:`SimpleTemplateResponse.resolve_template` using the context instance 100 returned by :meth:`SimpleTemplateResponse.resolve_context` and returns the 101 rendered content. 102 103 .. method:: SimpleTemplateResponse.bake(): 104 105 Bakes the response by setting :attr:`response.content` to the result 106 returned by :meth:`SimpleTemplateResponse.render`. 107 108 The response is baked by Django during response middleware cycle. You should 109 only bake the response yourself if it is to be used outside the 110 request-response cycle (e.g. for debugging). It will be baked twice 111 otherwise. 112 113 114 .. class:: TemplateResponse() 115 116 TemplateResponse is a subclass of 117 :class:`SimpleTemplateResponse <django.template.response.SimpleTemplateResponse>` 118 that uses RequestContext instead of Context. 119 120 .. method:: TemplateResponse.__init__(request, template, context=None, mimetype=None, status=None, content_type=None) 121 122 Instantiates an ``TemplateResponse`` object with the given template, 123 context, MIME type and HTTP status. 124 125 ``request`` is a HttpRequest instance. 126 127 ``template`` is a full name of a template to use or sequence of 128 template names. :class:`django.template.Template` instances are also 129 accepted. 130 131 ``context`` is a dictionary of values to add to the template context. 132 By default, this is an empty dictionary; context objects are also accepted 133 as ``context`` values. 134 135 ``status`` is the HTTP Status code for the response. 136 137 ``content_type`` is an alias for ``mimetype``. Historically, this parameter 138 was only called ``mimetype``, but since this is actually the value included 139 in the HTTP ``Content-Type`` header, it can also include the character set 140 encoding, which makes it more than just a MIME type specification. 141 If ``mimetype`` is specified (not ``None``), that value is used. 142 Otherwise, ``content_type`` is used. If neither is given, the 143 ``DEFAULT_CONTENT_TYPE`` setting is used. 144 145 146 Baking 147 ====== 148 149 *Baking* is the process by which the content in a TemplateResponse is 150 converted into the final form that will be returned to the client. 151 152 There are three circumstances under which a TemplateResponse is baked: 153 154 * When the TemplateResponse instance is explicitly baked, using 155 the :meth:`bake()` method. 156 157 * When the content of the response is explicitly set by assigning 158 :attr:`response.content`. 159 160 * After passing through template response middleware, but before 161 passing through response middleware. 162 163 A TemplateResponse can only be baked once. The first call to 164 :meth:`bake()` sets the content of the response; subsequent baking 165 calls do not change the response content. 166 167 However, when :attr:`response.content` is explicitly assigned, the 168 change is always applied. If you want to force templated content to be 169 rebaked, you can re-render the content and assign it:: 170 171 # Set up a baked TemplateResponse 172 >>> t = TemplateResponse(request, 'original.html', {}) 173 >>> t.bake() 174 >>> print t.content 175 Original content 176 177 # Rebaking doesn't change content 178 >>> t.template_name = 'other.html' 179 >>> t.bake() 180 >>> print t.content 181 Original content 182 183 # Assigning content does change 184 >>> t.content = t.render() 185 >>> print t.content 186 Other content 187 188 Using TemplateResponse and SimpleTemplateResponse 189 ================================================= 190 191 A TemplateResponse object can be used anywhere that a normal 192 HttpResponse can be used. It can also be used as an alternative to 193 calling render_to_response(). 194 195 For example, the following simple view returns a TemplateResponse 196 with a simple template, and a context containing a queryset:: 197 198 from django.template.response import TemplateResponse 199 200 def blog_index(request): 201 return TemplateResponse(request, 'entry_list.html', {'entries': Entry.objects.all()}) -
docs/topics/http/middleware.txt
diff -r 78ad3faa689b 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()`` is only called on response instances that 146 can be baked. It is called before the ``process_response()`` method. 147 148 You don't need to explicitly bake responses -- responses will be automatically baked 149 once all template response middleware has been called. 150 151 Middleware are run in reverse order during the response phase, which 152 includes process_template_response. 153 123 154 .. _exception-middleware: 124 155 125 156 ``process_exception`` … … 137 168 the browser. Otherwise, default exception handling kicks in. 138 169 139 170 Again, middleware are run in reverse order during the response phase, which 140 includes ``process_exception``. If an exception middleware return a response,171 includes ``process_exception``. If an exception middleware returns a response, 141 172 the middleware classes above that middleware will not be called at all. 142 173 143 174 ``__init__`` -
docs/topics/http/shortcuts.txt
diff -r 78ad3faa689b 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[, dictionary][, context_instance][, mimetype]) 19 20 Combines a given template with a given context dictionary and returns an 21 :class:`~django.http.HttpResponse` object with that rendered text. 22 23 :func:`render()` is the same as a call to 24 :func:`render_to_response()` with a context_instance argument that 25 that forces the use of a :class:`RequestContext`. 26 27 Required arguments 28 ------------------ 29 30 ``request`` 31 The request object used to generate this response. 32 33 ``template`` 34 The full name of a template to use or sequence of template names. 35 36 Optional arguments 37 ------------------ 38 39 ``dictionary`` 40 A dictionary of values to add to the template context. By default, this 41 is an empty dictionary. If a value in the dictionary is callable, the 42 view will call it just before rendering the template. 43 44 ``context_instance`` 45 The context instance to render the template with. By default, the template 46 will be rendered with a ``RequestContext`` instance (filled with values from 47 ``request`` and ```dictionary``). 48 49 ``mimetype`` 50 The MIME type to use for the resulting document. Defaults to the value of 51 the :setting:`DEFAULT_CONTENT_TYPE` setting. 52 53 Example 54 ------- 55 56 The following example renders the template ``myapp/index.html`` with the 57 MIME type ``application/xhtml+xml``:: 58 59 from django.shortcuts import render_to_response 60 61 def my_view(request): 62 # View code here... 63 return render_to_response('myapp/index.html', {"foo": "bar"}, 64 mimetype="application/xhtml+xml") 65 66 This example is equivalent to:: 67 68 from django.http import HttpResponse 69 from django.template import Context, loader 70 71 def my_view(request): 72 # View code here... 73 t = loader.get_template('myapp/template.html') 74 c = RequestContext(request, {'foo': 'bar'}) 75 return HttpResponse(t.render(c), 76 mimetype="application/xhtml+xml") 77 78 15 79 ``render_to_response`` 16 80 ====================== 17 81 -
tests/regressiontests/generic_views/base.py
diff -r 78ad3faa689b 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 78ad3faa689b tests/regressiontests/middleware_exceptions/tests.py
a b 3 3 from django.conf import settings 4 4 from django.core.signals import got_request_exception 5 5 from django.http import HttpResponse 6 from django.template.response import TemplateResponse 7 from django.template import Template 6 8 from django.test import TestCase 7 9 8 9 10 class TestException(Exception): 10 11 pass 11 12 … … 16 17 self.process_request_called = False 17 18 self.process_view_called = False 18 19 self.process_response_called = False 20 self.process_template_response_called = False 19 21 self.process_exception_called = False 20 22 21 23 def process_request(self, request): … … 24 26 def process_view(self, request, view_func, view_args, view_kwargs): 25 27 self.process_view_called = True 26 28 29 def process_template_response(self, request, response): 30 self.process_template_response_called = True 31 return response 32 27 33 def process_response(self, request, response): 28 34 self.process_response_called = True 29 35 return response … … 48 54 super(ResponseMiddleware, self).process_response(request, response) 49 55 return HttpResponse('Response Middleware') 50 56 57 class TemplateResponseMiddleware(TestMiddleware): 58 def process_template_response(self, request, response): 59 super(TemplateResponseMiddleware, self).process_template_response(request, response) 60 return TemplateResponse(request, Template('Template Response Middleware')) 61 51 62 class ExceptionMiddleware(TestMiddleware): 52 63 def process_exception(self, request, exception): 53 64 super(ExceptionMiddleware, self).process_exception(request, exception) … … 66 77 super(BadViewMiddleware, self).process_view(request, view_func, view_args, view_kwargs) 67 78 raise TestException('Test View Exception') 68 79 80 class BadTemplateResponseMiddleware(TestMiddleware): 81 def process_template_response(self, request, response): 82 super(BadTemplateResponseMiddleware, self).process_template_response(request, response) 83 raise TestException('Test Template Response Exception') 84 69 85 class BadResponseMiddleware(TestMiddleware): 70 86 def process_response(self, request, response): 71 87 super(BadResponseMiddleware, self).process_response(request, response) … … 93 109 def _add_middleware(self, middleware): 94 110 self.client.handler._request_middleware.insert(0, middleware.process_request) 95 111 self.client.handler._view_middleware.insert(0, middleware.process_view) 112 self.client.handler._template_response_middleware.append(middleware.process_template_response) 96 113 self.client.handler._response_middleware.append(middleware.process_response) 97 114 self.client.handler._exception_middleware.append(middleware.process_exception) 98 115 … … 113 130 exception, value, tb = self.exceptions[i] 114 131 self.assertEquals(value.args, (error, )) 115 132 116 def assert_middleware_usage(self, middleware, request, view, response, exception):133 def assert_middleware_usage(self, middleware, request, view, template_response, response, exception): 117 134 self.assertEqual(middleware.process_request_called, request) 118 135 self.assertEqual(middleware.process_view_called, view) 136 self.assertEqual(middleware.process_template_response_called, template_response) 119 137 self.assertEqual(middleware.process_response_called, response) 120 138 self.assertEqual(middleware.process_exception_called, exception) 121 139 … … 132 150 self.assert_exceptions_handled('/middleware_exceptions/view/', []) 133 151 134 152 # Check that the right middleware methods have been invoked 135 self.assert_middleware_usage(pre_middleware, True, False, True,False)136 self.assert_middleware_usage(middleware, True, False, True,False)137 self.assert_middleware_usage(post_middleware, False, False, True,False)153 self.assert_middleware_usage(pre_middleware, True, False, False, True, False) 154 self.assert_middleware_usage(middleware, True, False, False, True, False) 155 self.assert_middleware_usage(post_middleware, False, False, False, True, False) 138 156 139 157 def test_process_view_middleware(self): 140 158 pre_middleware = TestMiddleware() … … 146 164 self.assert_exceptions_handled('/middleware_exceptions/view/', []) 147 165 148 166 # Check that the right middleware methods have been invoked 149 self.assert_middleware_usage(pre_middleware, True, True,True, False)150 self.assert_middleware_usage(middleware, True, True,True, False)151 self.assert_middleware_usage(post_middleware, True, False, True, False)167 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 168 self.assert_middleware_usage(middleware, True, True, False, True, False) 169 self.assert_middleware_usage(post_middleware, True, False, False, True, False) 152 170 153 171 def test_process_response_middleware(self): 154 172 pre_middleware = TestMiddleware() … … 160 178 self.assert_exceptions_handled('/middleware_exceptions/view/', []) 161 179 162 180 # Check that the right middleware methods have been invoked 163 self.assert_middleware_usage(pre_middleware, True, True, True, False) 164 self.assert_middleware_usage(middleware, True, True, True, False) 165 self.assert_middleware_usage(post_middleware, True, True, True, False) 181 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 182 self.assert_middleware_usage(middleware, True, True, False, True, False) 183 self.assert_middleware_usage(post_middleware, True, True, False, True, False) 184 185 def test_process_template_response_middleware(self): 186 pre_middleware = TestMiddleware() 187 middleware = TemplateResponseMiddleware() 188 post_middleware = TestMiddleware() 189 self._add_middleware(post_middleware) 190 self._add_middleware(middleware) 191 self._add_middleware(pre_middleware) 192 self.assert_exceptions_handled('/middleware_exceptions/template_response/', []) 193 194 # Check that the right middleware methods have been invoked 195 self.assert_middleware_usage(pre_middleware, True, True, True, True, False) 196 self.assert_middleware_usage(middleware, True, True, True, True, False) 197 self.assert_middleware_usage(post_middleware, True, True, True, True, False) 166 198 167 199 def test_process_exception_middleware(self): 168 200 pre_middleware = TestMiddleware() … … 174 206 self.assert_exceptions_handled('/middleware_exceptions/view/', []) 175 207 176 208 # Check that the right middleware methods have been invoked 177 self.assert_middleware_usage(pre_middleware, True, True,True, False)178 self.assert_middleware_usage(middleware, True, True,True, False)179 self.assert_middleware_usage(post_middleware, True, True,True, False)209 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 210 self.assert_middleware_usage(middleware, True, True, False, True, False) 211 self.assert_middleware_usage(post_middleware, True, True, False, True, False) 180 212 181 213 def test_process_request_middleware_not_found(self): 182 214 pre_middleware = TestMiddleware() … … 188 220 self.assert_exceptions_handled('/middleware_exceptions/not_found/', []) 189 221 190 222 # Check that the right middleware methods have been invoked 191 self.assert_middleware_usage(pre_middleware, True, False, True,False)192 self.assert_middleware_usage(middleware, True, False, True,False)193 self.assert_middleware_usage(post_middleware, False, False, True,False)223 self.assert_middleware_usage(pre_middleware, True, False, False, True, False) 224 self.assert_middleware_usage(middleware, True, False, False, True, False) 225 self.assert_middleware_usage(post_middleware, False, False, False, True, False) 194 226 195 227 def test_process_view_middleware_not_found(self): 196 228 pre_middleware = TestMiddleware() … … 202 234 self.assert_exceptions_handled('/middleware_exceptions/not_found/', []) 203 235 204 236 # Check that the right middleware methods have been invoked 205 self.assert_middleware_usage(pre_middleware, True, True, True, False) 206 self.assert_middleware_usage(middleware, True, True, True, False) 207 self.assert_middleware_usage(post_middleware, True, False, True, False) 237 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 238 self.assert_middleware_usage(middleware, True, True, False, True, False) 239 self.assert_middleware_usage(post_middleware, True, False, False, True, False) 240 241 def test_process_template_response_middleware_not_found(self): 242 pre_middleware = TestMiddleware() 243 middleware = TemplateResponseMiddleware() 244 post_middleware = TestMiddleware() 245 self._add_middleware(post_middleware) 246 self._add_middleware(middleware) 247 self._add_middleware(pre_middleware) 248 self.assert_exceptions_handled('/middleware_exceptions/not_found/', []) 249 250 # Check that the right middleware methods have been invoked 251 self.assert_middleware_usage(pre_middleware, True, True, False, True, True) 252 self.assert_middleware_usage(middleware, True, True, False, True, True) 253 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 208 254 209 255 def test_process_response_middleware_not_found(self): 210 256 pre_middleware = TestMiddleware() … … 216 262 self.assert_exceptions_handled('/middleware_exceptions/not_found/', []) 217 263 218 264 # Check that the right middleware methods have been invoked 219 self.assert_middleware_usage(pre_middleware, True, True, True,True)220 self.assert_middleware_usage(middleware, True, True, True,True)221 self.assert_middleware_usage(post_middleware, True, True, True,True)265 self.assert_middleware_usage(pre_middleware, True, True, False, True, True) 266 self.assert_middleware_usage(middleware, True, True, False, True, True) 267 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 222 268 223 269 def test_process_exception_middleware_not_found(self): 224 270 pre_middleware = TestMiddleware() … … 230 276 self.assert_exceptions_handled('/middleware_exceptions/not_found/', []) 231 277 232 278 # Check that the right middleware methods have been invoked 233 self.assert_middleware_usage(pre_middleware, True, True,True, False)234 self.assert_middleware_usage(middleware, True, True, True,True)235 self.assert_middleware_usage(post_middleware, True, True, True,True)279 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 280 self.assert_middleware_usage(middleware, True, True, False, True, True) 281 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 236 282 237 283 def test_process_request_middleware_exception(self): 238 284 pre_middleware = TestMiddleware() … … 244 290 self.assert_exceptions_handled('/middleware_exceptions/error/', []) 245 291 246 292 # Check that the right middleware methods have been invoked 247 self.assert_middleware_usage(pre_middleware, True, False, True,False)248 self.assert_middleware_usage(middleware, True, False, True,False)249 self.assert_middleware_usage(post_middleware, False, False, True,False)293 self.assert_middleware_usage(pre_middleware, True, False, False, True, False) 294 self.assert_middleware_usage(middleware, True, False, False, True, False) 295 self.assert_middleware_usage(post_middleware, False, False, False, True, False) 250 296 251 297 def test_process_view_middleware_exception(self): 252 298 pre_middleware = TestMiddleware() … … 258 304 self.assert_exceptions_handled('/middleware_exceptions/error/', []) 259 305 260 306 # Check that the right middleware methods have been invoked 261 self.assert_middleware_usage(pre_middleware, True, True,True, False)262 self.assert_middleware_usage(middleware, True, True,True, False)263 self.assert_middleware_usage(post_middleware, True, False, True, False)307 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 308 self.assert_middleware_usage(middleware, True, True, False, True, False) 309 self.assert_middleware_usage(post_middleware, True, False, False, True, False) 264 310 265 311 def test_process_response_middleware_exception(self): 266 312 pre_middleware = TestMiddleware() … … 272 318 self.assert_exceptions_handled('/middleware_exceptions/error/', ['Error in view'], Exception()) 273 319 274 320 # Check that the right middleware methods have been invoked 275 self.assert_middleware_usage(pre_middleware, True, True, True,True)276 self.assert_middleware_usage(middleware, True, True, True,True)277 self.assert_middleware_usage(post_middleware, True, True, True,True)321 self.assert_middleware_usage(pre_middleware, True, True, False, True, True) 322 self.assert_middleware_usage(middleware, True, True, False, True, True) 323 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 278 324 279 325 def test_process_exception_middleware_exception(self): 280 326 pre_middleware = TestMiddleware() … … 286 332 self.assert_exceptions_handled('/middleware_exceptions/error/', []) 287 333 288 334 # Check that the right middleware methods have been invoked 289 self.assert_middleware_usage(pre_middleware, True, True,True, False)290 self.assert_middleware_usage(middleware, True, True, True,True)291 self.assert_middleware_usage(post_middleware, True, True, True,True)335 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 336 self.assert_middleware_usage(middleware, True, True, False, True, True) 337 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 292 338 293 339 def test_process_request_middleware_null_view(self): 294 340 pre_middleware = TestMiddleware() … … 300 346 self.assert_exceptions_handled('/middleware_exceptions/null_view/', []) 301 347 302 348 # Check that the right middleware methods have been invoked 303 self.assert_middleware_usage(pre_middleware, True, False, True,False)304 self.assert_middleware_usage(middleware, True, False, True,False)305 self.assert_middleware_usage(post_middleware, False, False, True,False)349 self.assert_middleware_usage(pre_middleware, True, False, False, True, False) 350 self.assert_middleware_usage(middleware, True, False, False, True, False) 351 self.assert_middleware_usage(post_middleware, False, False, False, True, False) 306 352 307 353 def test_process_view_middleware_null_view(self): 308 354 pre_middleware = TestMiddleware() … … 314 360 self.assert_exceptions_handled('/middleware_exceptions/null_view/', []) 315 361 316 362 # Check that the right middleware methods have been invoked 317 self.assert_middleware_usage(pre_middleware, True, True,True, False)318 self.assert_middleware_usage(middleware, True, True,True, False)319 self.assert_middleware_usage(post_middleware, True, False, True, False)363 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 364 self.assert_middleware_usage(middleware, True, True, False, True, False) 365 self.assert_middleware_usage(post_middleware, True, False, False, True, False) 320 366 321 367 def test_process_response_middleware_null_view(self): 322 368 pre_middleware = TestMiddleware() … … 331 377 ValueError()) 332 378 333 379 # Check that the right middleware methods have been invoked 334 self.assert_middleware_usage(pre_middleware, True, True, True,False)335 self.assert_middleware_usage(middleware, True, True, True,False)336 self.assert_middleware_usage(post_middleware, True, True, True,False)380 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 381 self.assert_middleware_usage(middleware, True, True, False, True, False) 382 self.assert_middleware_usage(post_middleware, True, True, False, True, False) 337 383 338 384 def test_process_exception_middleware_null_view(self): 339 385 pre_middleware = TestMiddleware() … … 348 394 ValueError()) 349 395 350 396 # Check that the right middleware methods have been invoked 351 self.assert_middleware_usage(pre_middleware, True, True,True, False)352 self.assert_middleware_usage(middleware, True, True,True, False)353 self.assert_middleware_usage(post_middleware, True, True,True, False)397 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 398 self.assert_middleware_usage(middleware, True, True, False, True, False) 399 self.assert_middleware_usage(post_middleware, True, True, False, True, False) 354 400 355 401 def test_process_request_middleware_permission_denied(self): 356 402 pre_middleware = TestMiddleware() … … 362 408 self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', []) 363 409 364 410 # Check that the right middleware methods have been invoked 365 self.assert_middleware_usage(pre_middleware, True, False, True,False)366 self.assert_middleware_usage(middleware, True, False, True,False)367 self.assert_middleware_usage(post_middleware, False, False, True,False)411 self.assert_middleware_usage(pre_middleware, True, False, False, True, False) 412 self.assert_middleware_usage(middleware, True, False, False, True, False) 413 self.assert_middleware_usage(post_middleware, False, False, False, True, False) 368 414 369 415 def test_process_view_middleware_permission_denied(self): 370 416 pre_middleware = TestMiddleware() … … 376 422 self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', []) 377 423 378 424 # Check that the right middleware methods have been invoked 379 self.assert_middleware_usage(pre_middleware, True, True,True, False)380 self.assert_middleware_usage(middleware, True, True,True, False)381 self.assert_middleware_usage(post_middleware, True, False, True, False)425 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 426 self.assert_middleware_usage(middleware, True, True, False, True, False) 427 self.assert_middleware_usage(post_middleware, True, False, False, True, False) 382 428 383 429 def test_process_response_middleware_permission_denied(self): 384 430 pre_middleware = TestMiddleware() … … 390 436 self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', []) 391 437 392 438 # Check that the right middleware methods have been invoked 393 self.assert_middleware_usage(pre_middleware, True, True, True,True)394 self.assert_middleware_usage(middleware, True, True, True,True)395 self.assert_middleware_usage(post_middleware, True, True, True,True)439 self.assert_middleware_usage(pre_middleware, True, True, False, True, True) 440 self.assert_middleware_usage(middleware, True, True, False, True, True) 441 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 396 442 397 443 def test_process_exception_middleware_permission_denied(self): 398 444 pre_middleware = TestMiddleware() … … 404 450 self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', []) 405 451 406 452 # Check that the right middleware methods have been invoked 407 self.assert_middleware_usage(pre_middleware, True, True, True, False) 408 self.assert_middleware_usage(middleware, True, True, True, True) 409 self.assert_middleware_usage(post_middleware, True, True, True, True) 453 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 454 self.assert_middleware_usage(middleware, True, True, False, True, True) 455 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 456 457 def test_process_template_response_error(self): 458 middleware = TestMiddleware() 459 self._add_middleware(middleware) 460 self.assert_exceptions_handled('/middleware_exceptions/template_response_error/', []) 461 462 # Check that the right middleware methods have been invoked 463 self.assert_middleware_usage(middleware, True, True, True, True, False) 464 410 465 411 466 class BadMiddlewareTests(BaseMiddlewareExceptionTest): 412 467 … … 420 475 self.assert_exceptions_handled('/middleware_exceptions/view/', ['Test Request Exception']) 421 476 422 477 # Check that the right middleware methods have been invoked 423 self.assert_middleware_usage(pre_middleware, True, False, True,False)424 self.assert_middleware_usage(bad_middleware, True, False, True,False)425 self.assert_middleware_usage(post_middleware, False, False, True,False)478 self.assert_middleware_usage(pre_middleware, True, False, False, True, False) 479 self.assert_middleware_usage(bad_middleware, True, False, False, True, False) 480 self.assert_middleware_usage(post_middleware, False, False, False, True, False) 426 481 427 482 def test_process_view_bad_middleware(self): 428 483 pre_middleware = TestMiddleware() … … 434 489 self.assert_exceptions_handled('/middleware_exceptions/view/', ['Test View Exception']) 435 490 436 491 # Check that the right middleware methods have been invoked 437 self.assert_middleware_usage(pre_middleware, True, True, True, False) 438 self.assert_middleware_usage(bad_middleware, True, True, True, False) 439 self.assert_middleware_usage(post_middleware, True, False, True, False) 492 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 493 self.assert_middleware_usage(bad_middleware, True, True, False, True, False) 494 self.assert_middleware_usage(post_middleware, True, False, False, True, False) 495 496 def test_process_template_response_bad_middleware(self): 497 pre_middleware = TestMiddleware() 498 bad_middleware = BadTemplateResponseMiddleware() 499 post_middleware = TestMiddleware() 500 self._add_middleware(post_middleware) 501 self._add_middleware(bad_middleware) 502 self._add_middleware(pre_middleware) 503 self.assert_exceptions_handled('/middleware_exceptions/template_response/', ['Test Template Response Exception']) 504 505 # Check that the right middleware methods have been invoked 506 self.assert_middleware_usage(pre_middleware, True, True, False, False, False) 507 self.assert_middleware_usage(bad_middleware, True, True, True, False, False) 508 self.assert_middleware_usage(post_middleware, True, True, True, False, False) 440 509 441 510 def test_process_response_bad_middleware(self): 442 511 pre_middleware = TestMiddleware() … … 448 517 self.assert_exceptions_handled('/middleware_exceptions/view/', ['Test Response Exception']) 449 518 450 519 # Check that the right middleware methods have been invoked 451 self.assert_middleware_usage(pre_middleware, True, True,False, False)452 self.assert_middleware_usage(bad_middleware, True, True,True, False)453 self.assert_middleware_usage(post_middleware, True, True,True, False)520 self.assert_middleware_usage(pre_middleware, True, True, False, False, False) 521 self.assert_middleware_usage(bad_middleware, True, True, False, True, False) 522 self.assert_middleware_usage(post_middleware, True, True, False, True, False) 454 523 455 524 def test_process_exception_bad_middleware(self): 456 525 pre_middleware = TestMiddleware() … … 462 531 self.assert_exceptions_handled('/middleware_exceptions/view/', []) 463 532 464 533 # Check that the right middleware methods have been invoked 465 self.assert_middleware_usage(pre_middleware, True, True,True, False)466 self.assert_middleware_usage(bad_middleware, True, True,True, False)467 self.assert_middleware_usage(post_middleware, True, True,True, False)534 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 535 self.assert_middleware_usage(bad_middleware, True, True, False, True, False) 536 self.assert_middleware_usage(post_middleware, True, True, False, True, False) 468 537 469 538 def test_process_request_bad_middleware_not_found(self): 470 539 pre_middleware = TestMiddleware() … … 476 545 self.assert_exceptions_handled('/middleware_exceptions/not_found/', ['Test Request Exception']) 477 546 478 547 # Check that the right middleware methods have been invoked 479 self.assert_middleware_usage(pre_middleware, True, False, True,False)480 self.assert_middleware_usage(bad_middleware, True, False, True,False)481 self.assert_middleware_usage(post_middleware, False, False, True,False)548 self.assert_middleware_usage(pre_middleware, True, False, False, True, False) 549 self.assert_middleware_usage(bad_middleware, True, False, False, True, False) 550 self.assert_middleware_usage(post_middleware, False, False, False, True, False) 482 551 483 552 def test_process_view_bad_middleware_not_found(self): 484 553 pre_middleware = TestMiddleware() … … 490 559 self.assert_exceptions_handled('/middleware_exceptions/not_found/', ['Test View Exception']) 491 560 492 561 # Check that the right middleware methods have been invoked 493 self.assert_middleware_usage(pre_middleware, True, True,True, False)494 self.assert_middleware_usage(bad_middleware, True, True,True, False)495 self.assert_middleware_usage(post_middleware, True, False, True, False)562 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 563 self.assert_middleware_usage(bad_middleware, True, True, False, True, False) 564 self.assert_middleware_usage(post_middleware, True, False, False, True, False) 496 565 497 566 def test_process_response_bad_middleware_not_found(self): 498 567 pre_middleware = TestMiddleware() … … 504 573 self.assert_exceptions_handled('/middleware_exceptions/not_found/', ['Test Response Exception']) 505 574 506 575 # Check that the right middleware methods have been invoked 507 self.assert_middleware_usage(pre_middleware, True, True,False, True)508 self.assert_middleware_usage(bad_middleware, True, True,True, True)509 self.assert_middleware_usage(post_middleware, True, True,True, True)576 self.assert_middleware_usage(pre_middleware, True, True, False, False, True) 577 self.assert_middleware_usage(bad_middleware, True, True, False, True, True) 578 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 510 579 511 580 def test_process_exception_bad_middleware_not_found(self): 512 581 pre_middleware = TestMiddleware() … … 518 587 self.assert_exceptions_handled('/middleware_exceptions/not_found/', ['Test Exception Exception']) 519 588 520 589 # Check that the right middleware methods have been invoked 521 self.assert_middleware_usage(pre_middleware, True, True,True, False)522 self.assert_middleware_usage(bad_middleware, True, True, True,True)523 self.assert_middleware_usage(post_middleware, True, True, True,True)590 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 591 self.assert_middleware_usage(bad_middleware, True, True, False, True, True) 592 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 524 593 525 594 def test_process_request_bad_middleware_exception(self): 526 595 pre_middleware = TestMiddleware() … … 532 601 self.assert_exceptions_handled('/middleware_exceptions/error/', ['Test Request Exception']) 533 602 534 603 # Check that the right middleware methods have been invoked 535 self.assert_middleware_usage(pre_middleware, True, False, True,False)536 self.assert_middleware_usage(bad_middleware, True, False, True,False)537 self.assert_middleware_usage(post_middleware, False, False, True,False)604 self.assert_middleware_usage(pre_middleware, True, False, False, True, False) 605 self.assert_middleware_usage(bad_middleware, True, False, False, True, False) 606 self.assert_middleware_usage(post_middleware, False, False, False, True, False) 538 607 539 608 def test_process_view_bad_middleware_exception(self): 540 609 pre_middleware = TestMiddleware() … … 546 615 self.assert_exceptions_handled('/middleware_exceptions/error/', ['Test View Exception']) 547 616 548 617 # Check that the right middleware methods have been invoked 549 self.assert_middleware_usage(pre_middleware, True, True,True, False)550 self.assert_middleware_usage(bad_middleware, True, True,True, False)551 self.assert_middleware_usage(post_middleware, True, False, True, False)618 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 619 self.assert_middleware_usage(bad_middleware, True, True, False, True, False) 620 self.assert_middleware_usage(post_middleware, True, False, False, True, False) 552 621 553 622 def test_process_response_bad_middleware_exception(self): 554 623 pre_middleware = TestMiddleware() … … 560 629 self.assert_exceptions_handled('/middleware_exceptions/error/', ['Error in view', 'Test Response Exception']) 561 630 562 631 # Check that the right middleware methods have been invoked 563 self.assert_middleware_usage(pre_middleware, True, True,False, True)564 self.assert_middleware_usage(bad_middleware, True, True,True, True)565 self.assert_middleware_usage(post_middleware, True, True,True, True)632 self.assert_middleware_usage(pre_middleware, True, True, False, False, True) 633 self.assert_middleware_usage(bad_middleware, True, True, False, True, True) 634 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 566 635 567 636 def test_process_exception_bad_middleware_exception(self): 568 637 pre_middleware = TestMiddleware() … … 574 643 self.assert_exceptions_handled('/middleware_exceptions/error/', ['Test Exception Exception']) 575 644 576 645 # Check that the right middleware methods have been invoked 577 self.assert_middleware_usage(pre_middleware, True, True,True, False)578 self.assert_middleware_usage(bad_middleware, True, True, True,True)579 self.assert_middleware_usage(post_middleware, True, True, True,True)646 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 647 self.assert_middleware_usage(bad_middleware, True, True, False, True, True) 648 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 580 649 581 650 def test_process_request_bad_middleware_null_view(self): 582 651 pre_middleware = TestMiddleware() … … 588 657 self.assert_exceptions_handled('/middleware_exceptions/null_view/', ['Test Request Exception']) 589 658 590 659 # Check that the right middleware methods have been invoked 591 self.assert_middleware_usage(pre_middleware, True, False, True,False)592 self.assert_middleware_usage(bad_middleware, True, False, True,False)593 self.assert_middleware_usage(post_middleware, False, False, True,False)660 self.assert_middleware_usage(pre_middleware, True, False, False, True, False) 661 self.assert_middleware_usage(bad_middleware, True, False, False, True, False) 662 self.assert_middleware_usage(post_middleware, False, False, False, True, False) 594 663 595 664 def test_process_view_bad_middleware_null_view(self): 596 665 pre_middleware = TestMiddleware() … … 602 671 self.assert_exceptions_handled('/middleware_exceptions/null_view/', ['Test View Exception']) 603 672 604 673 # Check that the right middleware methods have been invoked 605 self.assert_middleware_usage(pre_middleware, True, True,True, False)606 self.assert_middleware_usage(bad_middleware, True, True,True, False)607 self.assert_middleware_usage(post_middleware, True, False, True, False)674 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 675 self.assert_middleware_usage(bad_middleware, True, True, False, True, False) 676 self.assert_middleware_usage(post_middleware, True, False, False, True, False) 608 677 609 678 def test_process_response_bad_middleware_null_view(self): 610 679 pre_middleware = TestMiddleware() … … 619 688 ]) 620 689 621 690 # Check that the right middleware methods have been invoked 622 self.assert_middleware_usage(pre_middleware, True, True,False, False)623 self.assert_middleware_usage(bad_middleware, True, True,True, False)624 self.assert_middleware_usage(post_middleware, True, True,True, False)691 self.assert_middleware_usage(pre_middleware, True, True, False, False, False) 692 self.assert_middleware_usage(bad_middleware, True, True, False, True, False) 693 self.assert_middleware_usage(post_middleware, True, True, False, True, False) 625 694 626 695 def test_process_exception_bad_middleware_null_view(self): 627 696 pre_middleware = TestMiddleware() … … 636 705 ValueError()) 637 706 638 707 # Check that the right middleware methods have been invoked 639 self.assert_middleware_usage(pre_middleware, True, True,True, False)640 self.assert_middleware_usage(bad_middleware, True, True,True, False)641 self.assert_middleware_usage(post_middleware, True, True,True, False)708 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 709 self.assert_middleware_usage(bad_middleware, True, True, False, True, False) 710 self.assert_middleware_usage(post_middleware, True, True, False, True, False) 642 711 643 712 def test_process_request_bad_middleware_permission_denied(self): 644 713 pre_middleware = TestMiddleware() … … 650 719 self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', ['Test Request Exception']) 651 720 652 721 # Check that the right middleware methods have been invoked 653 self.assert_middleware_usage(pre_middleware, True, False, True,False)654 self.assert_middleware_usage(bad_middleware, True, False, True,False)655 self.assert_middleware_usage(post_middleware, False, False, True,False)722 self.assert_middleware_usage(pre_middleware, True, False, False, True, False) 723 self.assert_middleware_usage(bad_middleware, True, False, False, True, False) 724 self.assert_middleware_usage(post_middleware, False, False, False, True, False) 656 725 657 726 def test_process_view_bad_middleware_permission_denied(self): 658 727 pre_middleware = TestMiddleware() … … 664 733 self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', ['Test View Exception']) 665 734 666 735 # Check that the right middleware methods have been invoked 667 self.assert_middleware_usage(pre_middleware, True, True,True, False)668 self.assert_middleware_usage(bad_middleware, True, True,True, False)669 self.assert_middleware_usage(post_middleware, True, False, True, False)736 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 737 self.assert_middleware_usage(bad_middleware, True, True, False, True, False) 738 self.assert_middleware_usage(post_middleware, True, False, False, True, False) 670 739 671 740 def test_process_response_bad_middleware_permission_denied(self): 672 741 pre_middleware = TestMiddleware() … … 678 747 self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', ['Test Response Exception']) 679 748 680 749 # Check that the right middleware methods have been invoked 681 self.assert_middleware_usage(pre_middleware, True, True,False, True)682 self.assert_middleware_usage(bad_middleware, True, True,True, True)683 self.assert_middleware_usage(post_middleware, True, True,True, True)750 self.assert_middleware_usage(pre_middleware, True, True, False, False, True) 751 self.assert_middleware_usage(bad_middleware, True, True, False, True, True) 752 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 684 753 685 754 def test_process_exception_bad_middleware_permission_denied(self): 686 755 pre_middleware = TestMiddleware() … … 692 761 self.assert_exceptions_handled('/middleware_exceptions/permission_denied/', ['Test Exception Exception']) 693 762 694 763 # Check that the right middleware methods have been invoked 695 self.assert_middleware_usage(pre_middleware, True, True,True, False)696 self.assert_middleware_usage(bad_middleware, True, True, True,True)697 self.assert_middleware_usage(post_middleware, True, True, True,True)764 self.assert_middleware_usage(pre_middleware, True, True, False, True, False) 765 self.assert_middleware_usage(bad_middleware, True, True, False, True, True) 766 self.assert_middleware_usage(post_middleware, True, True, False, True, True) 698 767 699 768 700 769 _missing = object() -
tests/regressiontests/middleware_exceptions/urls.py
diff -r 78ad3faa689b 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 78ad3faa689b 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 78ad3faa689b 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 ContentNotBakedError) 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 # rebaking doesn't change the baked content 71 response.template_name = Template('bar{{ baz }}') 72 response.bake() 73 self.assertEqual(response.content, 'foo') 74 75 # but baked content can be overridden by manually 76 # setting content 77 response.content = 'bar' 78 self.assertEqual(response.content, 'bar') 79 80 def test_iteration_unbaked(self): 81 # unbaked response raises an exception on iteration 82 response = self._response() 83 self.assertFalse(response.baked) 84 85 def iteration(): 86 for x in response: 87 pass 88 self.assertRaises(ContentNotBakedError, iteration) 89 self.assertFalse(response.baked) 90 91 def test_iteration_baked(self): 92 # iteration works for baked responses 93 response = self._response().bake() 94 res = [x for x in response] 95 self.assertEqual(res, ['foo']) 96 97 def test_content_access_unbaked(self): 98 # unbaked response raises an exception when content is accessed 99 response = self._response() 100 self.assertFalse(response.baked) 101 self.assertRaises(ContentNotBakedError, lambda: response.content) 102 self.assertFalse(response.baked) 103 104 def test_content_access_baked(self): 105 # baked response content can be accessed 106 response = self._response().bake() 107 self.assertEqual(response.content, 'foo') 108 109 def test_set_content(self): 110 # content can be overriden 111 response = self._response() 112 self.assertFalse(response.baked) 113 response.content = 'spam' 114 self.assertTrue(response.baked) 115 self.assertEqual(response.content, 'spam') 116 response.content = 'baz' 117 self.assertEqual(response.content, 'baz') 118 119 def test_dict_context(self): 120 response = self._response('{{ foo }}{{ processors }}', 121 {'foo': 'bar'}) 122 self.assertEqual(response.context_data, {'foo': 'bar'}) 123 response.bake() 124 self.assertEqual(response.content, 'bar') 125 126 def test_context_instance(self): 127 response = self._response('{{ foo }}{{ processors }}', 128 Context({'foo': 'bar'})) 129 self.assertEqual(response.context_data.__class__, Context) 130 response.bake() 131 self.assertEqual(response.content, 'bar') 132 133 def test_kwargs(self): 134 response = self._response(content_type = 'application/json', status=504) 135 self.assertEqual(response['content-type'], 'application/json') 136 self.assertEqual(response.status_code, 504) 137 138 def test_args(self): 139 response = SimpleTemplateResponse('', {}, 'application/json', 504) 140 self.assertEqual(response['content-type'], 'application/json') 141 self.assertEqual(response.status_code, 504) 142 143 144 class TemplateResponseTest(BaseTemplateResponseTest): 145 146 def _response(self, template='foo', *args, **kwargs): 147 return TemplateResponse(self.factory.get('/'), Template(template), 148 *args, **kwargs) 149 150 def test_render(self): 151 response = self._response('{{ foo }}{{ processors }}').bake() 152 self.assertEqual(response.content, 'yes') 153 154 def test_render_with_requestcontext(self): 155 response = self._response('{{ foo }}{{ processors }}', 156 {'foo': 'bar'}).bake() 157 self.assertEqual(response.content, 'baryes') 158 159 def test_render_with_context(self): 160 response = self._response('{{ foo }}{{ processors }}', 161 Context({'foo': 'bar'})).bake() 162 self.assertEqual(response.content, 'bar') 163 164 def test_kwargs(self): 165 response = self._response(content_type = 'application/json', 166 status=504) 167 self.assertEqual(response['content-type'], 'application/json') 168 self.assertEqual(response.status_code, 504) 169 170 def test_args(self): 171 response = TemplateResponse(self.factory.get('/'), '', {}, 172 'application/json', 504) 173 self.assertEqual(response['content-type'], 'application/json') 174 self.assertEqual(response.status_code, 504) -
tests/regressiontests/templates/tests.py
diff -r 78ad3faa689b tests/regressiontests/templates/tests.py
a b 28 28 from unicode import UnicodeTests 29 29 from nodelist import NodelistTest 30 30 from smartif import * 31 from response import * 31 32 32 33 try: 33 34 from loaders import * -
new file tests/regressiontests/views/templates/debug/render_test.html
diff -r 78ad3faa689b tests/regressiontests/views/templates/debug/render_test.html
- + 1 {{ foo }}.{{ bar }}.{{ baz }}.{{ processors }} -
tests/regressiontests/views/tests/__init__.py
diff -r 78ad3faa689b 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 78ad3faa689b 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 test_view(request): 8 return render(request, 'debug/render_test.html', 9 {'foo': 'foo', 'baz': 'baz'}) 10 11 12 class RenderTest(BaseTemplateResponseTest): 13 14 def setUp(self): 15 super(RenderTest, self).setUp() 16 self.request = self.factory.get('/') 17 18 def test_simple_view(self): 19 response = test_view(self.request) 20 self.assertEqual(response.content, 'foo..baz.yes\n')