| 1 |
""" |
| 2 |
A set of request processors that return dictionaries to be merged into a |
| 3 |
template context. Each function takes the request object as its only parameter |
| 4 |
and returns a dictionary to add to the context. |
| 5 |
|
| 6 |
These are referenced from the 'context_processors' option of the configuration |
| 7 |
of a DjangoTemplates backend and used by RequestContext. |
| 8 |
""" |
| 9 |
|
| 10 |
import itertools |
| 11 |
|
| 12 |
from django.conf import settings |
| 13 |
from django.middleware.csrf import get_token |
| 14 |
from django.utils.functional import SimpleLazyObject, lazy |
| 15 |
|
| 16 |
|
| 17 |
def csrf(request): |
| 18 |
""" |
| 19 |
Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if |
| 20 |
it has not been provided by either a view decorator or the middleware |
| 21 |
""" |
| 22 |
|
| 23 |
def _get_val(): |
| 24 |
token = get_token(request) |
| 25 |
if token is None: |
| 26 |
# In order to be able to provide debugging info in the |
| 27 |
# case of misconfiguration, we use a sentinel value |
| 28 |
# instead of returning an empty dict. |
| 29 |
return "NOTPROVIDED" |
| 30 |
else: |
| 31 |
return token |
| 32 |
|
| 33 |
return {"csrf_token": SimpleLazyObject(_get_val)} |
| 34 |
|
| 35 |
|
| 36 |
def debug(request): |
| 37 |
""" |
| 38 |
Return context variables helpful for debugging. |
| 39 |
""" |
| 40 |
context_extras = {} |
| 41 |
if settings.DEBUG and request.META.get("REMOTE_ADDR") in settings.INTERNAL_IPS: |
| 42 |
context_extras["debug"] = True |
| 43 |
from django.db import connections |
| 44 |
|
| 45 |
# Return a lazy reference that computes connection.queries on access, |
| 46 |
# to ensure it contains queries triggered after this function runs. |
| 47 |
context_extras["sql_queries"] = lazy( |
| 48 |
lambda: list( |
| 49 |
itertools.chain.from_iterable( |
| 50 |
connections[x].queries for x in connections |
| 51 |
) |
| 52 |
), |
| 53 |
list, |
| 54 |
) |
| 55 |
return context_extras |
| 56 |
|
| 57 |
|
| 58 |
def i18n(request): |
| 59 |
from django.utils import translation |
| 60 |
|
| 61 |
return { |
| 62 |
"LANGUAGES": settings.LANGUAGES, |
| 63 |
"LANGUAGE_CODE": translation.get_language(), |
| 64 |
"LANGUAGE_BIDI": translation.get_language_bidi(), |
| 65 |
} |
| 66 |
|
| 67 |
|
| 68 |
def tz(request): |
| 69 |
from django.utils import timezone |
| 70 |
|
| 71 |
return {"TIME_ZONE": timezone.get_current_timezone_name()} |
| 72 |
|
| 73 |
|
| 74 |
def static(request): |
| 75 |
""" |
| 76 |
Add static-related context variables to the context. |
| 77 |
""" |
| 78 |
return {"STATIC_URL": settings.STATIC_URL} |
| 79 |
|
| 80 |
|
| 81 |
def media(request): |
| 82 |
""" |
| 83 |
Add media-related context variables to the context. |
| 84 |
""" |
| 85 |
return {"MEDIA_URL": settings.MEDIA_URL} |
| 86 |
|
| 87 |
|
| 88 |
def request(request): |
| 89 |
return {"request": request} |