context_processors.py 2.6 KB

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