Files
andwati.com/content/writings/generate-django-secret-key/index.md
T
andwati 1b7c4039e3 Migrate legacy Zola posts into content/writings/ (additive)
scripts/migrate-posts-to-writings.mjs converts all 20 posts under
content/posts/ into the new writings schema — normalizes dates to
bare TOML local-dates, converts the one unambiguous Zola shortcode in
use (youtube embeds) to a plain <iframe>, and strips the now-meaningless
{% raw %}/{% endraw %} escape tags. content/posts/ itself is untouched;
this only adds content/writings/*.

Also generates 301 redirects from the old /posts/<slug>/ URLs to the
new /writings/<slug>/ ones into sws.toml, inside marker comments so
re-running the script regenerates that block idempotently instead of
duplicating it.

Two posts (from-c-to-machine-code, self-hosting-gitea-and-mirroring-github)
use note/tip/warning/danger callout shortcodes that have no Astro
equivalent yet — flagged by the script rather than guessed at, since
that needs a real component once the design system exists.

Verified: astro check clean, full site builds (80 pages, all real
migrated posts render), redirect generation confirmed idempotent
across repeated runs.
2026-08-30 19:10:53 +03:00

1.6 KiB

+++ title = "Django Secret Key Tutorial" description = "Managing secrets" author = "andwati" date = 2022-11-11 draft = false

[taxonomies] tags = [ "tutorial", "django", "python", ".env" ]

+++

Managing the Django SECRET_KEY variable.

The Django SECRET_KEY variable is very crucial to your Django application. The secret key must be a large random value and it must be kept secret. Leaking this value to unauthorized people could lead to a security breach. The SECRET_KEY is used in Django for cryptographic signing. It is used to generate tokens and hashes, they can be recreated using this variable. If it is not configured Django throws a django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty error

Using Environment Variables

The secret key should not be committed to version control. It is best practice to store the value in a .env file which is added to the .gitignore file to un-track its changes. The values can be loaded programmatically into your settings.py file.

Generating A New Secret Key

This solution is using python's secrets lib on the back

from django.core.management.utils import get_random_secret_key
# print new random secret key
print(get_random_secret_key())

This code can be run in the terminal as a command:

python -c 'from django.core.management.utils import get_random_secret_key; \
            print(get_random_secret_key())'

Alternatively, If you are using python 3.6+ then you can use the secrets.token_hex(\[nbytes=None]) function:

python3 -c 'import secrets; print(secrets.token_hex(100))'