Files
andwati-nextgen/content/writing/generate-django-secret-key.md
T
andwati 63007a1c09 Rebuild site in Tailwind to match adammaj.com layout with andwati content
- Port adammaj.com layout, sidebar and 3D bookshelf from Chakra to Tailwind v4,
  matched to measured pixel values
- Pages: About, Writing, Reading (bookshelf), Portfolio; content exported to
  markdown with YAML frontmatter, KaTeX math, callouts and YouTube embeds
- Shiki (github-light) code highlighting via rehype-pretty-code
- SEO: per-page metadata and canonicals, JSON-LD, generated OG images,
  sitemap, robots, RSS/JSON feeds, llms.txt
- Umami analytics via PUBLIC_UMAMI_SCRIPT_URL / PUBLIC_UMAMI_WEBSITE_ID
- Prettier + cspell for content, husky/lint-staged pre-commit hook
- Multi-stage Dockerfile (Node 24, pnpm, standalone output) for Dokploy
- Remove unused Chakra, emotion, framer-motion, posthog, next-seo and MDX deps
2026-09-30 12:38:09 +03:00

1.5 KiB

title, description, date, tags
title description date tags
Django Secret Key Tutorial Managing secrets 2022-11-11
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))'