Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 77 ยท Middleware, Signals and Internals

Logging, Email and Internationalization

Configure Django's LOGGING dict, send and test email with EmailMessage, translate text with gettext, and handle time zones correctly with USE_TZ.

Four features turn a working site into a professional one, and they have something in common: each is configured in settings.py, and each is easy to get slightly wrong. Logging tells you what your site is doing when nobody is watching. Email reaches users outside the browser. Internationalization (often written i18n) lets one codebase speak many languages. Time zone support keeps dates and times correct for people all over the world.

This lesson gives you a working mental model of each, with live examples. Django's built-in pieces for all four rely on the Python standard library underneath (the logging, email, gettext and zoneinfo modules), so what you learn transfers. If you want the plain-Python background, see logging and warnings and dates and times.

Logging

Django uses Python's standard logging module and lets you configure it through one setting, LOGGING, which is a dictionary in the dictConfig format. It has four ingredients:

  • Loggers receive messages from your code. Their names form a hierarchy with dots: shop.orders is a child of shop.
  • Handlers decide where messages go (the console, a file, email).
  • Formatters decide what a line looks like.
  • Levels filter by importance: DEBUG, INFO, WARNING, ERROR, CRITICAL.
flowchart LR
    C["logger.info(...)<br/>in your code"] --> L["Logger<br/>shop.orders"]
    L -->|"level check"| H["Handler<br/>console / file"]
    H --> F["Formatter"]
    F --> O["Output line"]
    L -.->|"propagate"| P["Parent logger<br/>shop"]

A message passes the logger's level, goes to its handlers, and (unless propagation is off) continues to the parent logger.

By convention each module creates a logger with logging.getLogger(__name__). Then the logger name tells you where a line came from, and you can turn one part of the project up or down without touching the others. Django itself logs through loggers such as django.request (4xx and 5xx responses), django.db.backends (every SQL query, at DEBUG level) and django.security.

The example configures two loggers, writes to the console, and lets a request to a missing page show Django's own logging.

Python Configuring LOGGING

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Study which lines appeared. The DEBUG call on shop.orders was dropped because the parent's level is INFO, but shop.payments set its own DEBUG level, so its debug line was shown. Child loggers use the handlers of their ancestors through propagation, which is why shop.payments did not need a handler of its own. The ERROR line passed every check and was formatted with the same pattern. Django's own django.request logger reported the 404 automatically, because we gave it a handler too. A logger with no handler anywhere in its chain falls back to Python's "last resort" handler, which prints only warnings and above, without your format.

A few good habits:

  • Pass values as arguments (logger.info("order %s", order_id)), not through f-strings. The formatting is skipped when the message is filtered out, and log tools can group identical messages.
  • Use logger.exception(...) inside except blocks: it logs at ERROR level and appends the traceback of the exception being handled.
  • Never log passwords, tokens or full card numbers.
  • In production, send ERROR messages somewhere people will see them: an error-tracking service, or Django's AdminEmailHandler, which emails the addresses in the ADMINS setting.

Sending email

Django's email API wraps Python's smtplib and MIME machinery. You choose a backend with EMAIL_BACKEND:

Backend Behavior
django.core.mail.backends.smtp.EmailBackend Sends through an SMTP server (the production default)
django.core.mail.backends.console.EmailBackend Prints emails to the terminal; handy in development
django.core.mail.backends.filebased.EmailBackend Writes each email to a file
django.core.mail.backends.locmem.EmailBackend Collects emails in a list; used automatically by Django's tests
django.core.mail.backends.dummy.EmailBackend Does nothing

A typical SMTP configuration reads its secrets from the environment and is read-only here, because a browser tab cannot reach an SMTP server:

Python
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.example.com"
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = os.environ["EMAIL_USER"]
EMAIL_HOST_PASSWORD = os.environ["EMAIL_PASSWORD"]
DEFAULT_FROM_EMAIL = "Shop <[email protected]>"

For simple messages use send_mail(). For control over headers, attachments and an HTML alternative, build an EmailMultiAlternatives (or EmailMessage for plain text). The next example uses the locmem backend so you can inspect what would have been sent.

Python Sending email with the locmem backend

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a real project you will usually render the body from templates with render_to_string(), one for text and one for HTML. Two cautions: sending email inside a request makes the page wait for the mail server, so move slow or bulk sending into a background job, and never trust user input in headers (Django rejects newlines in subject and addresses to block header injection).

In tests, Django swaps in the locmem backend automatically and gives you mail.outbox, so you can assert that "the welcome email was sent" without any real mail server.

Internationalization

Django separates three ideas that are easy to mix up:

  • Internationalization (i18n): preparing code so text can be translated.
  • Localization (l10n): formatting dates, numbers and similar values for a locale.
  • Translation itself: the catalogs of translated strings.

You mark text for translation with gettext (usually imported as _). Translatable strings in module-level code such as model fields or form labels must use gettext_lazy, which delays the lookup until the string is displayed, because the active language is only known per request. Plurals use ngettext.

Python
from django.utils.translation import gettext as _, gettext_lazy, ngettext

title = _("Welcome")                       # in a view: translated now
label = gettext_lazy("Email address")      # in a model or form: translated when displayed
text = ngettext("%(count)d item", "%(count)d items", count) % {"count": count}

In templates, load the library and use {% trans "Welcome" %} or {% blocktranslate %}...{% endblocktranslate %} for blocks with variables. The workflow on your own machine is: run python manage.py makemessages -l fr to extract the marked strings into a .po file, translate them, then run python manage.py compilemessages to create the binary .mo file. A LocaleMiddleware picks the language per request from the URL prefix, a cookie or the browser's Accept-Language header.

We cannot create .po files in the browser, but Django itself is translated into dozens of languages, so we can switch the language and watch Django's built-in messages change. The translation.override() context manager sets the active language for a block of code.

Python Switching languages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The lazy string was created once, yet it printed differently in each block. That is exactly why labels in models and forms must be lazy: they are defined when the module loads, long before any language is chosen. The form error and the date format changed too, because both look up the active language when they are produced.

Time zones

Dates and times are a classic source of bugs. Django's rule is simple and worth memorizing: store UTC, display local time. With USE_TZ = True (the default in new projects) Django stores every DateTimeField as an aware UTC value, and converts to the user's time zone only for display. TIME_ZONE sets the default zone for templates and forms.

Key functions in django.utils.timezone:

  • now() returns the current aware datetime. Use it instead of datetime.now(), which is naive.
  • localtime(value) converts an aware value to the current time zone.
  • make_aware(naive, tz) attaches a zone to a naive datetime you built yourself.
  • override("Asia/Tokyo") temporarily switches the current zone, for instance to render a page in each user's own zone.
Python Aware datetimes and time zones

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

(The example installs the small tzdata package because a browser has no operating-system time zone database; on most servers it is already there.) The same instant shows as three different wall-clock times, and 9:00 in New York is a different UTC time in January than in July because of daylight saving time. Storing UTC avoids the headaches this causes; only convert at the edges. With USE_TZ = True, saving a naive datetime to the database triggers a warning, a helpful sign that you forgot a time zone.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A logger named 'shop.orders' has no handler of its own. Why can its messages still appear on the console?

    By default a logger passes its records up the dotted hierarchy, so the handlers of 'shop' (and the root logger) also see them unless propagate is False.
  2. 2. Which is the better way to log a value?

    Passing arguments lets logging skip the formatting when the message is filtered out and lets tools group identical messages.
  3. 3. What does the locmem email backend do?

    It keeps sent messages in memory, which is why Django's test runner uses it and why you can assert on mail.outbox.
  4. 4. Why use gettext_lazy for a model field's verbose_name?

    Model and form definitions run at import time, before any request chooses a language. A lazy string looks up the translation each time it is displayed.
  5. 5. With USE_TZ = True, what does Django store in a DateTimeField column?

    Storing UTC keeps data unambiguous. Conversion to a user's zone happens when values are displayed or entered.

Summary

  • LOGGING is a dictConfig dictionary of loggers, handlers, formatters and levels; use logging.getLogger(__name__) and pass values as arguments.
  • Child loggers propagate to parent handlers; logger.exception() records tracebacks.
  • Pick an EMAIL_BACKEND (SMTP in production, console or locmem otherwise); build messages with send_mail, EmailMessage or EmailMultiAlternatives.
  • Mark text with gettext or gettext_lazy, plurals with ngettext; the workflow is makemessages, translate, compilemessages.
  • Store UTC with USE_TZ = True; use timezone.now(), localtime() and make_aware().

Next lesson: Building JSON APIs with Plain Django.