Moved context_processors from django.core to django.template.

This commit is contained in:
Aymeric Augustin 2014-12-02 23:23:51 +01:00
parent c599f233b1
commit 92e8f1f302
20 changed files with 152 additions and 134 deletions

View File

@ -218,12 +218,12 @@ TEMPLATE_LOADERS = (
# only parameter and returns a dictionary to add to the context. # only parameter and returns a dictionary to add to the context.
TEMPLATE_CONTEXT_PROCESSORS = ( TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth', 'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug', 'django.template.context_processors.debug',
'django.core.context_processors.i18n', 'django.template.context_processors.i18n',
'django.core.context_processors.media', 'django.template.context_processors.media',
'django.core.context_processors.static', 'django.template.context_processors.static',
'django.core.context_processors.tz', 'django.template.context_processors.tz',
# 'django.core.context_processors.request', # 'django.template.context_processors.request',
'django.contrib.messages.context_processors.messages', 'django.contrib.messages.context_processors.messages',
) )

View File

@ -60,11 +60,11 @@ TEMPLATES = [
'APP_DIRS': True, 'APP_DIRS': True,
'OPTIONS': { 'OPTIONS': {
'context_processors': [ 'context_processors': [
'django.core.context_processors.debug', 'django.template.context_processors.debug',
'django.core.context_processors.i18n', 'django.template.context_processors.i18n',
'django.core.context_processors.tz', 'django.template.context_processors.tz',
'django.core.context_processors.media', 'django.template.context_processors.media',
'django.core.context_processors.static', 'django.template.context_processors.static',
'django.contrib.auth.context_processors.auth', 'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages', 'django.contrib.messages.context_processors.messages',
], ],

View File

@ -1,85 +1,10 @@
""" import warnings
A set of request processors that return dictionaries to be merged into a
template context. Each function takes the request object as its only parameter
and returns a dictionary to add to the context.
These are referenced from the setting TEMPLATE_CONTEXT_PROCESSORS and used by from django.template.context_processors import * # NOQA
RequestContext. from django.utils.deprecation import RemovedInDjango20Warning
"""
from __future__ import unicode_literals
from django.conf import settings
from django.middleware.csrf import get_token
from django.utils import six
from django.utils.encoding import smart_text
from django.utils.functional import lazy
def csrf(request): warnings.warn(
""" "django.core.context_processors is deprecated in favor of "
Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if "django.template.context_processors.",
it has not been provided by either a view decorator or the middleware RemovedInDjango20Warning, stacklevel=2)
"""
def _get_val():
token = get_token(request)
if token is None:
# In order to be able to provide debugging info in the
# case of misconfiguration, we use a sentinel value
# instead of returning an empty dict.
return 'NOTPROVIDED'
else:
return smart_text(token)
_get_val = lazy(_get_val, six.text_type)
return {'csrf_token': _get_val()}
def debug(request):
"""
Returns context variables helpful for debugging.
"""
context_extras = {}
if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
context_extras['debug'] = True
from django.db import connection
# Return a lazy reference that computes connection.queries on access,
# to ensure it contains queries triggered after this function runs.
context_extras['sql_queries'] = lazy(lambda: connection.queries, list)
return context_extras
def i18n(request):
from django.utils import translation
context_extras = {}
context_extras['LANGUAGES'] = settings.LANGUAGES
context_extras['LANGUAGE_CODE'] = translation.get_language()
context_extras['LANGUAGE_BIDI'] = translation.get_language_bidi()
return context_extras
def tz(request):
from django.utils import timezone
return {'TIME_ZONE': timezone.get_current_timezone_name()}
def static(request):
"""
Adds static-related context variables to the context.
"""
return {'STATIC_URL': settings.STATIC_URL}
def media(request):
"""
Adds media-related context variables to the context.
"""
return {'MEDIA_URL': settings.MEDIA_URL}
def request(request):
return {'request': request}

View File

@ -2,7 +2,7 @@ from copy import copy
# Hard-coded processor for easier use of CSRF protection. # Hard-coded processor for easier use of CSRF protection.
_builtin_context_processors = ('django.core.context_processors.csrf',) _builtin_context_processors = ('django.template.context_processors.csrf',)
class ContextPopException(Exception): class ContextPopException(Exception):

View File

@ -0,0 +1,85 @@
"""
A set of request processors that return dictionaries to be merged into a
template context. Each function takes the request object as its only parameter
and returns a dictionary to add to the context.
These are referenced from the setting TEMPLATE_CONTEXT_PROCESSORS and used by
RequestContext.
"""
from __future__ import unicode_literals
from django.conf import settings
from django.middleware.csrf import get_token
from django.utils import six
from django.utils.encoding import smart_text
from django.utils.functional import lazy
def csrf(request):
"""
Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
it has not been provided by either a view decorator or the middleware
"""
def _get_val():
token = get_token(request)
if token is None:
# In order to be able to provide debugging info in the
# case of misconfiguration, we use a sentinel value
# instead of returning an empty dict.
return 'NOTPROVIDED'
else:
return smart_text(token)
_get_val = lazy(_get_val, six.text_type)
return {'csrf_token': _get_val()}
def debug(request):
"""
Returns context variables helpful for debugging.
"""
context_extras = {}
if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
context_extras['debug'] = True
from django.db import connection
# Return a lazy reference that computes connection.queries on access,
# to ensure it contains queries triggered after this function runs.
context_extras['sql_queries'] = lazy(lambda: connection.queries, list)
return context_extras
def i18n(request):
from django.utils import translation
context_extras = {}
context_extras['LANGUAGES'] = settings.LANGUAGES
context_extras['LANGUAGE_CODE'] = translation.get_language()
context_extras['LANGUAGE_BIDI'] = translation.get_language_bidi()
return context_extras
def tz(request):
from django.utils import timezone
return {'TIME_ZONE': timezone.get_current_timezone_name()}
def static(request):
"""
Adds static-related context variables to the context.
"""
return {'STATIC_URL': settings.STATIC_URL}
def media(request):
"""
Adds media-related context variables to the context.
"""
return {'MEDIA_URL': settings.MEDIA_URL}
def request(request):
return {'request': request}

View File

@ -44,6 +44,8 @@ details on these changes.
:class:`~django.core.management.BaseCommand` instead, which takes no arguments :class:`~django.core.management.BaseCommand` instead, which takes no arguments
by default. by default.
* ``django.core.context_processors`` module will be removed.
* ``django.db.models.sql.aggregates`` module will be removed. * ``django.db.models.sql.aggregates`` module will be removed.
* ``django.contrib.gis.db.models.sql.aggregates`` module will be removed. * ``django.contrib.gis.db.models.sql.aggregates`` module will be removed.

View File

@ -381,7 +381,7 @@ There are a few other helpers outside of the
:mod:`staticfiles <django.contrib.staticfiles>` app to work with static :mod:`staticfiles <django.contrib.staticfiles>` app to work with static
files: files:
- The :func:`django.core.context_processors.static` context processor - The :func:`django.template.context_processors.static` context processor
which adds :setting:`STATIC_URL` to every template context rendered which adds :setting:`STATIC_URL` to every template context rendered
with :class:`~django.template.RequestContext` contexts. with :class:`~django.template.RequestContext` contexts.

View File

@ -46,11 +46,11 @@ To take advantage of CSRF protection in your views, follow these steps:
that would cause the CSRF token to be leaked, leading to a vulnerability. that would cause the CSRF token to be leaked, leading to a vulnerability.
3. In the corresponding view functions, ensure that the 3. In the corresponding view functions, ensure that the
``'django.core.context_processors.csrf'`` context processor is ``'django.template.context_processors.csrf'`` context processor is
being used. Usually, this can be done in one of two ways: being used. Usually, this can be done in one of two ways:
1. Use RequestContext, which always uses 1. Use RequestContext, which always uses
``'django.core.context_processors.csrf'`` (no matter what your ``'django.template.context_processors.csrf'`` (no matter what your
TEMPLATE_CONTEXT_PROCESSORS setting). If you are using TEMPLATE_CONTEXT_PROCESSORS setting). If you are using
generic views or contrib apps, you are covered already, since these generic views or contrib apps, you are covered already, since these
apps use RequestContext throughout. apps use RequestContext throughout.
@ -58,8 +58,8 @@ To take advantage of CSRF protection in your views, follow these steps:
2. Manually import and use the processor to generate the CSRF token and 2. Manually import and use the processor to generate the CSRF token and
add it to the template context. e.g.:: add it to the template context. e.g.::
from django.core.context_processors import csrf
from django.shortcuts import render_to_response from django.shortcuts import render_to_response
from django.template.context_processors import csrf
def my_view(request): def my_view(request):
c = {} c = {}

View File

@ -1863,7 +1863,7 @@ to a non-empty value. You will need to :ref:`configure these files to be served
<serving-uploaded-files-in-development>` in both development and production. <serving-uploaded-files-in-development>` in both development and production.
In order to use ``{{ MEDIA_URL }}`` in your templates, you must have In order to use ``{{ MEDIA_URL }}`` in your templates, you must have
``'django.core.context_processors.media'`` in your ``'django.template.context_processors.media'`` in your
:setting:`TEMPLATE_CONTEXT_PROCESSORS`. It's there by default, but be sure :setting:`TEMPLATE_CONTEXT_PROCESSORS`. It's there by default, but be sure
to include it if you override that setting and want this behavior. to include it if you override that setting and want this behavior.
@ -2382,11 +2382,11 @@ TEMPLATE_CONTEXT_PROCESSORS
Default:: Default::
("django.contrib.auth.context_processors.auth", ("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug", "django.template.context_processors.debug",
"django.core.context_processors.i18n", "django.template.context_processors.i18n",
"django.core.context_processors.media", "django.template.context_processors.media",
"django.core.context_processors.static", "django.template.context_processors.static",
"django.core.context_processors.tz", "django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages") "django.contrib.messages.context_processors.messages")
A tuple of callables that are used to populate the context in ``RequestContext``. A tuple of callables that are used to populate the context in ``RequestContext``.

View File

@ -457,15 +457,15 @@ and return a dictionary of items to be merged into the context. By default,
:setting:`TEMPLATE_CONTEXT_PROCESSORS` is set to:: :setting:`TEMPLATE_CONTEXT_PROCESSORS` is set to::
("django.contrib.auth.context_processors.auth", ("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug", "django.template.context_processors.debug",
"django.core.context_processors.i18n", "django.template.context_processors.i18n",
"django.core.context_processors.media", "django.template.context_processors.media",
"django.core.context_processors.static", "django.template.context_processors.static",
"django.core.context_processors.tz", "django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages") "django.contrib.messages.context_processors.messages")
In addition to these, ``RequestContext`` always uses In addition to these, ``RequestContext`` always uses
``django.core.context_processors.csrf``. This is a security ``django.template.context_processors.csrf``. This is a security
related context processor required by the admin and other contrib apps, and, related context processor required by the admin and other contrib apps, and,
in case of accidental misconfiguration, it is deliberately hardcoded in and in case of accidental misconfiguration, it is deliberately hardcoded in and
cannot be turned off by the :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting. cannot be turned off by the :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting.
@ -526,10 +526,10 @@ If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
``django.contrib.auth.context_processors.PermWrapper``, representing the ``django.contrib.auth.context_processors.PermWrapper``, representing the
permissions that the currently logged-in user has. permissions that the currently logged-in user has.
.. currentmodule:: django.core.context_processors .. currentmodule:: django.template.context_processors
django.core.context_processors.debug django.template.context_processors.debug
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
``RequestContext`` will contain these two variables -- but only if your ``RequestContext`` will contain these two variables -- but only if your
@ -543,8 +543,8 @@ If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
and how long it took. The list is in order by query and lazily generated and how long it took. The list is in order by query and lazily generated
on access. on access.
django.core.context_processors.i18n django.template.context_processors.i18n
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
``RequestContext`` will contain these two variables: ``RequestContext`` will contain these two variables:
@ -555,15 +555,15 @@ If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
See :doc:`/topics/i18n/index` for more. See :doc:`/topics/i18n/index` for more.
django.core.context_processors.media django.template.context_processors.media
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
``RequestContext`` will contain a variable ``MEDIA_URL``, providing the ``RequestContext`` will contain a variable ``MEDIA_URL``, providing the
value of the :setting:`MEDIA_URL` setting. value of the :setting:`MEDIA_URL` setting.
django.core.context_processors.static django.template.context_processors.static
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. function:: static .. function:: static
@ -571,15 +571,15 @@ If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
``RequestContext`` will contain a variable ``STATIC_URL``, providing the ``RequestContext`` will contain a variable ``STATIC_URL``, providing the
value of the :setting:`STATIC_URL` setting. value of the :setting:`STATIC_URL` setting.
django.core.context_processors.csrf django.template.context_processors.csrf
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This processor adds a token that is needed by the :ttag:`csrf_token` template This processor adds a token that is needed by the :ttag:`csrf_token` template
tag for protection against :doc:`Cross Site Request Forgeries tag for protection against :doc:`Cross Site Request Forgeries
</ref/csrf>`. </ref/csrf>`.
django.core.context_processors.request django.template.context_processors.request
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
``RequestContext`` will contain a variable ``request``, which is the current ``RequestContext`` will contain a variable ``request``, which is the current

View File

@ -1014,6 +1014,12 @@ Related to the previous item, referencing views as strings in the ``url()``
function is deprecated. Pass the callable view as described in the previous function is deprecated. Pass the callable view as described in the previous
section instead. section instead.
``django.core.context_processors``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Built-in template context processors have been moved to
``django.template.context_processors``.
``django.test.SimpleTestCase.urls`` ``django.test.SimpleTestCase.urls``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

View File

@ -311,7 +311,7 @@ time zone is unset, the default time zone applies.
get_current_timezone get_current_timezone
~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~
When the ``django.core.context_processors.tz`` context processor is When the ``django.template.context_processors.tz`` context processor is
enabled -- by default, it is -- each :class:`~django.template.RequestContext` enabled -- by default, it is -- each :class:`~django.template.RequestContext`
contains a ``TIME_ZONE`` variable that provides the name of the current time contains a ``TIME_ZONE`` variable that provides the name of the current time
zone. zone.

View File

@ -28,7 +28,7 @@ bit of i18n-related overhead in certain places of the framework. If you don't
use internationalization, you should take the two seconds to set use internationalization, you should take the two seconds to set
:setting:`USE_I18N = False <USE_I18N>` in your settings file. Then Django will :setting:`USE_I18N = False <USE_I18N>` in your settings file. Then Django will
make some optimizations so as not to load the internationalization machinery. make some optimizations so as not to load the internationalization machinery.
You'll probably also want to remove ``'django.core.context_processors.i18n'`` You'll probably also want to remove ``'django.template.context_processors.i18n'``
from your :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting. from your :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting.
.. note:: .. note::
@ -1509,7 +1509,7 @@ back to the previous page.
Make sure that the following item is in your Make sure that the following item is in your
:setting:`TEMPLATE_CONTEXT_PROCESSORS` list in your settings file:: :setting:`TEMPLATE_CONTEXT_PROCESSORS` list in your settings file::
'django.core.context_processors.i18n' 'django.template.context_processors.i18n'
Activate this view by adding the following line to your URLconf:: Activate this view by adding the following line to your URLconf::

View File

@ -4344,7 +4344,7 @@ class ValidXHTMLTests(TestCase):
@override_settings( @override_settings(
TEMPLATE_CONTEXT_PROCESSORS=filter( TEMPLATE_CONTEXT_PROCESSORS=filter(
lambda t: t != 'django.core.context_processors.i18n', lambda t: t != 'django.template.context_processors.i18n',
global_settings.TEMPLATE_CONTEXT_PROCESSORS), global_settings.TEMPLATE_CONTEXT_PROCESSORS),
USE_I18N=False, USE_I18N=False,
) )

View File

@ -20,7 +20,6 @@ from django.core import signals
from django.core.cache import (cache, caches, CacheKeyWarning, from django.core.cache import (cache, caches, CacheKeyWarning,
InvalidCacheBackendError, DEFAULT_CACHE_ALIAS, get_cache, InvalidCacheBackendError, DEFAULT_CACHE_ALIAS, get_cache,
close_caches) close_caches)
from django.core.context_processors import csrf
from django.db import connection, connections, transaction from django.db import connection, connections, transaction
from django.core.cache.utils import make_template_fragment_key from django.core.cache.utils import make_template_fragment_key
from django.http import HttpResponse, StreamingHttpResponse from django.http import HttpResponse, StreamingHttpResponse
@ -28,6 +27,7 @@ from django.middleware.cache import (FetchFromCacheMiddleware,
UpdateCacheMiddleware, CacheMiddleware) UpdateCacheMiddleware, CacheMiddleware)
from django.middleware.csrf import CsrfViewMiddleware from django.middleware.csrf import CsrfViewMiddleware
from django.template import Template from django.template import Template
from django.template.context_processors import csrf
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from django.test import TestCase, TransactionTestCase, RequestFactory, override_settings from django.test import TestCase, TransactionTestCase, RequestFactory, override_settings
from django.test.signals import setting_changed from django.test.signals import setting_changed

View File

@ -7,7 +7,7 @@ from django.test import TestCase, override_settings
@override_settings(ROOT_URLCONF='context_processors.urls') @override_settings(ROOT_URLCONF='context_processors.urls')
class RequestContextProcessorTests(TestCase): class RequestContextProcessorTests(TestCase):
""" """
Tests for the ``django.core.context_processors.request`` processor. Tests for the ``django.template.context_processors.request`` processor.
""" """
def test_request_attributes(self): def test_request_attributes(self):
@ -38,7 +38,7 @@ class RequestContextProcessorTests(TestCase):
@override_settings(ROOT_URLCONF='context_processors.urls', DEBUG=True, INTERNAL_IPS=('127.0.0.1',)) @override_settings(ROOT_URLCONF='context_processors.urls', DEBUG=True, INTERNAL_IPS=('127.0.0.1',))
class DebugContextProcessorTests(TestCase): class DebugContextProcessorTests(TestCase):
""" """
Tests for the ``django.core.context_processors.debug`` processor. Tests for the ``django.template.context_processors.debug`` processor.
""" """
def test_debug(self): def test_debug(self):

View File

@ -1,5 +1,5 @@
from django.core import context_processors
from django.shortcuts import render_to_response from django.shortcuts import render_to_response
from django.template import context_processors
from django.template.context import RequestContext from django.template.context import RequestContext
from .models import DebugObject from .models import DebugObject

View File

@ -3,10 +3,10 @@ from __future__ import unicode_literals
import logging import logging
from django.conf import settings from django.conf import settings
from django.core.context_processors import csrf
from django.http import HttpRequest, HttpResponse from django.http import HttpRequest, HttpResponse
from django.middleware.csrf import CsrfViewMiddleware, CSRF_KEY_LENGTH from django.middleware.csrf import CsrfViewMiddleware, CSRF_KEY_LENGTH
from django.template import RequestContext, Template from django.template import RequestContext, Template
from django.template.context_processors import csrf
from django.test import TestCase, override_settings from django.test import TestCase, override_settings
from django.views.decorators.csrf import csrf_exempt, requires_csrf_token, ensure_csrf_cookie from django.views.decorators.csrf import csrf_exempt, requires_csrf_token, ensure_csrf_cookie

View File

@ -4,7 +4,7 @@ from django.test import TestCase, override_settings
@override_settings( @override_settings(
TEMPLATE_CONTEXT_PROCESSORS=('django.core.context_processors.static',), TEMPLATE_CONTEXT_PROCESSORS=('django.template.context_processors.static',),
STATIC_URL='/path/to/static/media/', STATIC_URL='/path/to/static/media/',
ROOT_URLCONF='shortcuts.urls', ROOT_URLCONF='shortcuts.urls',
) )

View File

@ -932,7 +932,7 @@ class TemplateTests(TestCase):
@skipIf(sys.platform.startswith('win'), "Windows uses non-standard time zone names") @skipIf(sys.platform.startswith('win'), "Windows uses non-standard time zone names")
def test_tz_template_context_processor(self): def test_tz_template_context_processor(self):
""" """
Test the django.core.context_processors.tz template context processor. Test the django.template.context_processors.tz template context processor.
""" """
tpl = Template("{{ TIME_ZONE }}") tpl = Template("{{ TIME_ZONE }}")
self.assertEqual(tpl.render(Context()), "") self.assertEqual(tpl.render(Context()), "")