Django and manage.py commands cheat sheet

This cheat sheet brings together the manage.py commands you need to manage a Django project on a server: settings for each environment, database migrations, static files, checks before going live, users, data backup, and fixes for common errors. You can search for a command, filter by topic, and copy it with one click.

Project and settings

  • django-admin startproject myproject .

    Creates a new project in the current directory: the manage.py file and a myproject directory with settings.py, urls.py, wsgi.py, and asgi.py. Run it inside the virtual environment where Django is installed.

  • python manage.py startapp blog

    Creates a new app inside the project, with models.py and views.py files and a migrations directory. Then add the app's name to the INSTALLED_APPS list in the settings file.

  • python manage.py help

    Lists all the commands available in the project, including commands added by apps and packages. With a command name, for example python manage.py help migrate, it shows all the options of that command.

  • export DJANGO_SETTINGS_MODULE=myproject.settings

    Sets which settings file Django loads, written as a Python module path. The manage.py file sets the variable to the project's settings file only when it isn't already set, so on the server you can choose a different settings file for each environment.

  • python manage.py migrate --settings=myproject.settings.production

    Runs a single command with a specific settings file, without changing the environment variable. The --settings option is available in every command.

  • python manage.py diffsettings

    Shows only the settings that differ from the Django defaults. With --all, it shows every setting, and with --output unified, the output is in diff style. The output includes sensitive values such as SECRET_KEY and the database password, so don't share it.

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

    Generates a random 50-character string to use as SECRET_KEY. This is the function startproject uses to create the key for a new project. Run it in an environment where Django is installed.

  • import os SECRET_KEY = os.environ["SECRET_KEY"]

    Loads the secret key from an environment variable instead of keeping it in the code, as the deployment checklist in the Django documentation shows. Do the same for the database password and other sensitive values. Set the variables on the server, for example in a file the systemd service loads with EnvironmentFile.

Database migrations

  • python manage.py makemigrations

    Creates migration files based on the changes to the models. Run it in the development environment, review the output, and commit the migration files to the code repository together with the model changes. On the production server, you only run the migrations.

  • python manage.py makemigrations blog --name add_author

    Creates a migration for a single app, with a clear name instead of the automatically generated one.

  • python manage.py makemigrations --check

    Exits with an error code when there are model changes without a migration, without creating any files. Useful in an automated check before deployment.

  • python manage.py migrate

    Applies to the database all the migrations that haven't run yet. This is the command you run on the server after every code update, and you back up the database before it.

  • python manage.py migrate --plan

    Shows which operations would run, without actually running them.

  • python manage.py migrate --check

    Exits with an error code when there are unapplied migrations. Useful in a deployment script, so new code doesn't start on an old database schema.

  • python manage.py showmigrations

    Lists the migrations of each app, and a migration that has already run is marked with [X]. With --plan, it lists all the migrations in the order they run.

  • python manage.py sqlmigrate blog 0003

    Shows the SQL statements the migration would run, without actually running them. With --backwards, it shows the SQL that reverses the migration.

  • python manage.py migrate blog 0002

    Returns the blog app to its state after migration 0002, which means it reverses the migrations that came after it. Reversing a migration can drop columns and tables along with their data, and migrations that depend on it are reversed too. Back up the database first.

  • python manage.py migrate blog zero

    Reverses all the migrations of the app, which usually drops all its tables and the data in them. A dangerous command on a production server.

  • python manage.py migrate blog 0004 --fake

    Marks a migration as applied without running its SQL. Use it only when the change already exists in the database. According to the Django documentation, using it the wrong way can leave the migrations table in a state that needs manual repair.

  • python manage.py migrate --fake-initial

    Skips the initial migration of an app when its tables already exist, for example after connecting to an existing database. Django checks only the table names, not the columns.

  • python manage.py makemigrations --merge

    Creates a merge migration when two code branches added migrations to the same app at the same time.

  • python manage.py squashmigrations blog 0004

    Squashes the migrations of the app up to 0004 into a single file. Keep the old files until every environment has run the squashed file, and only then delete them.

Static and media files

  • STATIC_URL = "static/" STATIC_ROOT = "/home/deploy/app/staticfiles/"

    STATIC_ROOT is the directory that collectstatic copies all the static files to, and the web server serves it at the STATIC_URL address. It starts out empty and is used only for deployment, so don't put files in it by hand.

  • python manage.py collectstatic --noinput

    Collects the CSS, JavaScript, and image files of all the apps, including the Django admin, into the STATIC_ROOT directory. The --noinput option skips the confirmation prompt, which suits a deployment script. Run it after every change to the static files.

  • python manage.py collectstatic --noinput --clear

    First deletes all the files in the STATIC_ROOT directory, and then collects them again. Useful after you remove an app and old files are left behind.

  • python manage.py collectstatic --dry-run --noinput

    Shows what would be collected, without changing any files on disk.

  • python manage.py findstatic css/base.css

    Shows which directory a specific static file is taken from. Helpful when two apps contain a file with the same name.

  • MEDIA_URL = "media/" MEDIA_ROOT = "/home/deploy/app/media/"

    Media files are the files users upload to the site, and they're stored in MEDIA_ROOT. The directory must be different from STATIC_ROOT. The Django documentation warns that uploaded files can't be trusted, so the web server should serve them only as files and never execute them.

Checks before going live

  • python manage.py check

    Runs the Django system checks on the models, URLs, and settings, and shows errors and warnings. Most commands also run these checks on their own before they start.

  • python manage.py check --deploy

    Adds the checks for a production server: DEBUG, SECRET_KEY, secure cookies, the HTTPS redirect, and more. Run it with the production settings file.

  • python manage.py check --deploy --fail-level WARNING

    Exits with an error code on warnings too, not only on errors. This way a deployment script stops when a setting was forgotten.

  • DEBUG = False ALLOWED_HOSTS = ["example.com", "www.example.com"]

    On a production server, DEBUG is always off, because the detailed error page exposes code, variables, and settings. When DEBUG is off, Django doesn't work at all without the list of domains in ALLOWED_HOSTS. A value that starts with a dot, for example .example.com, matches the domain and all its subdomains.

  • CSRF_TRUSTED_ORIGINS = ["https://example.com", "https://*.example.com"]

    Trusted origins for POST requests, including the scheme. The setting is needed when a form is submitted from another domain, or when the domain the visitor sees differs from the domain that reaches Django.

  • SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")

    Behind Nginx that handles HTTPS, the request reaches Django over http, and this setting lets Django recognize that the visitor connected over HTTPS. Set it only when Nginx removes the X-Forwarded-Proto header sent by the visitor and sets it itself, or else a visitor can forge it.

  • SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True

    The login cookie and the CSRF cookie are sent only over HTTPS, so they can't be intercepted on an unencrypted connection. These settings suit any site that runs on HTTPS.

  • SECURE_SSL_REDIRECT = True

    Redirects every http request to the HTTPS address. When this setting causes a redirect loop, Django doesn't recognize that the request came over HTTPS through the proxy, and the fix is SECURE_PROXY_SSL_HEADER. You can also leave the redirect to Nginx.

Running on the server

  • gunicorn myproject.wsgi

    Runs the project with Gunicorn through the application object in the myproject/wsgi.py file. Run it from the directory that contains manage.py. The full setup, including workers, a systemd service, and Nginx, is on the Python in production page.

  • python -m uvicorn myproject.asgi:application

    Runs the project in ASGI mode through the myproject/asgi.py file, for an application that uses async code or WebSockets.

  • python manage.py runserver

    The built-in development server, which listens on 127.0.0.1:8000 by default and reloads the code on every change. It's meant for development only: the Django documentation explicitly says not to use it on a production server.

  • /home/deploy/app/.venv/bin/python /home/deploy/app/manage.py clearsessions

    Deletes expired sessions when the sessions are stored in the database. Django doesn't delete them on its own, so run the command from cron, for example once a day, with the full path to the interpreter of the virtual environment.

Users

  • python manage.py createsuperuser

    Creates an admin user with full access to the Django admin. The command asks for a username, an email address, and a password.

  • python manage.py createsuperuser --noinput --username admin --email admin@example.com

    Creates an admin user without prompts, for example in a setup script. The password is taken from the DJANGO_SUPERUSER_PASSWORD environment variable, which you set beforehand in the script's environment. Without the variable, the user is created without a password and can't log in until you set one.

  • python manage.py changepassword admin

    Changes the password of an existing user, for example when an admin forgot the password to the Django admin. Without a username, the command changes the password of the user whose name matches the user running it on the server.

Shell, database, and data backup

  • python manage.py shell

    Opens an interactive Python shell with the project's settings, so you can work with the models directly. The models of the apps are imported automatically.

  • python manage.py shell -c 'from django.contrib.auth import get_user_model; print(get_user_model().objects.count())'

    Runs a piece of Python code without opening a shell, for example for a quick check or from a script. The example shows the number of users on the site.

  • python manage.py dbshell

    Opens the database client, for example psql or mysql, with the connection details from the project's settings. The client must be installed on the server.

  • python manage.py dbshell -- -c 'select current_user'

    Passes everything after -- to the database client. In the example, psql for PostgreSQL runs one query and exits. In MySQL, the matching option is -e.

  • python manage.py inspectdb > legacy_models.py

    Generates models from the tables of an existing database, for example when you move an old system to Django. The models are created with managed = False, and you review and fix them by hand before you use them.

  • python manage.py dumpdata --natural-foreign --natural-primary -e contenttypes -e auth.Permission --indent 2 -o data.json

    Saves the project's data to a JSON file. The contenttypes and auth.Permission tables, which Django creates on its own during migrate, are left out, and natural keys let you load the file into a different database. A .gz extension in the file name saves it compressed.

  • python manage.py dumpdata blog.Post --indent 2 -o posts.json

    Saves only one model or one app. A good fit for moving content, not for a full backup: to back up the database, use its own backup tool.

  • python manage.py loaddata data.json

    Loads data from a file created with dumpdata. A record that already exists in the database with the same primary key is replaced with the data from the file.

  • python manage.py flush

    Deletes all the data from every table in the database, except the list of migrations that have run. A dangerous command: it can't be undone, and you don't run it on a production server.

Tests and translations

  • python manage.py test

    Runs the project's automated tests on a temporary test database, which is deleted at the end. The data of the site itself doesn't change.

  • python manage.py test blog --parallel --keepdb

    Runs the tests of one app in several processes at once, by default one process per core. With --keepdb, the test database is kept between runs, so they start faster.

  • python manage.py makemessages -l he

    Collects the strings to translate from the code and the templates into the locale/he/LC_MESSAGES/django.po file. With -a, all existing languages are updated. Requires the gettext tools on the server.

  • python manage.py compilemessages

    Compiles the .po translation files into .mo files, which are what Django actually loads. Run it after every translation update, on the server too.

Common errors

  • ALLOWED_HOSTS = ["example.com", "www.example.com"]

    The DisallowedHost error shows the message Invalid HTTP_HOST header: 'example.com'. You may need to add 'example.com' to ALLOWED_HOSTS, and the visitor gets 400 Bad Request. The domain in the request isn't on the list. Add it, including the www version, and restart the service.

  • SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") CSRF_TRUSTED_ORIGINS = ["https://example.com"]

    The error Forbidden (403) CSRF verification failed. Request aborted, with the reason Origin checking failed - https://example.com does not match any trusted origins, appears when you submit a form behind HTTPS. Django sees an http request and compares the origin with the wrong address. Make sure Nginx sends the X-Forwarded-Proto and Host headers, set SECURE_PROXY_SSL_HEADER, and if needed, add the address to CSRF_TRUSTED_ORIGINS.

  • python manage.py collectstatic --noinput

    CSS files and the Django admin load without styling and return 404 after you turn off DEBUG. When DEBUG is off, Django doesn't serve static files: run collectstatic and configure the web server to serve STATIC_ROOT at the STATIC_URL address.

  • python manage.py showmigrations | grep '\[ \]'

    The error no such table or relation does not exist, or the message You have 3 unapplied migration(s) at startup, means there are migrations that haven't run. The command lists the migrations that haven't run yet, and then you run python manage.py migrate.

  • sudo systemctl cat myapp

    The error ImproperlyConfigured: The SECRET_KEY setting must not be empty means the secret key didn't reach the project, usually because the environment variable isn't set in the service. The command shows the service file, so you can check that the EnvironmentFile line points to the right file and that the variable is set in it.

  • export DJANGO_SETTINGS_MODULE=myproject.settings

    The message Requested setting ..., but settings are not configured appears when you run Django code without manage.py, for example from a script or with django-admin, and Django doesn't know which settings file to load.

  • python manage.py makemigrations --merge

    The error Conflicting migrations detected; multiple leaf nodes in the migration graph means two migrations of the same app were created at the same time, usually in two code branches. The command creates a merge migration, and then you run migrate.

  • python manage.py dbshell

    The error django.db.utils.OperationalError when connecting to the database usually means the database server isn't running, the host or port is wrong, or the password is incorrect. The command tries to connect with exactly the same settings and shows the error from the database.

  • python manage.py check --deploy

    Before every launch, and after a change to the settings, the check shows missing security settings. You can silence a warning whose setting isn't relevant to your site in the SILENCED_SYSTEM_CHECKS list.

Every Django project has a manage.py file, which does the same thing as the django-admin command, with one difference: it sets DJANGO_SETTINGS_MODULE to the project's settings file. Run the commands from the directory that contains manage.py, with the interpreter of the project's virtual environment. The commands for creating the environment and installing packages are on the pip and venv commands page.

Settings that change between development and production, such as DEBUG, SECRET_KEY, and the database details, are usually read from environment variables, or kept in a separate settings file for each environment and chosen with DJANGO_SETTINGS_MODULE. The wsgi.py and asgi.py files also set the variable only when it isn't already set. Static files are part of the code and are collected with collectstatic, while media files are the files users upload, so they're kept in a separate directory and included in the backup.

On a production server, the project runs with Gunicorn or Uvicorn as a systemd service, and Nginx in front of it receives the requests, handles the SSL certificate, and serves the static files. The full setup is on the Python in production page and the Nginx cheat sheet, and 502 and 504 errors are explained on the 500, 502, 503, and 504 server errors page. For the database, see PostgreSQL commands and Common MySQL errors, and for caching and sessions in Redis, see Redis commands. Set up recurring tasks such as clearsessions in cron, and build the schedule expression with the cron expression generator.

Django comes with more commands, for example sendtestemail to test the email settings, and apps and packages can add commands of their own. The full list is shown by python manage.py help. The project, app, and path names on this page are examples, so replace them with your project's values.

Did you know?

On a Python VPS, the environment comes ready: Python, pip, and venv are installed and configured, and you get full root access over SSH, so you install Django in a virtual environment, run migrate and collectstatic, and launch your site. On a Linux VPS, you connect over SSH with full root access and set up everything on this page, from the database to the web server.

Python VPS plans

Django commands FAQ

What's the difference between django-admin and python manage.py?

Both run the same commands. Every project has a manage.py file that presets the project's settings file, so for everyday work in an existing project, you run python manage.py. The django-admin command is used mainly to create a new project with startproject, or when you choose a settings file with DJANGO_SETTINGS_MODULE or with --settings.

Which commands do I run on every Django site update?

After you upload the new code, install the packages from the requirements.txt file in the virtual environment, run python manage.py migrate to update the database and python manage.py collectstatic --noinput to update the static files, and finally reload the Gunicorn or Uvicorn service. It's also a good idea to run python manage.py check --deploy, which shows missing security settings before the site goes live.

Why did my site lose its styling after I turned off DEBUG?

When DEBUG is on, the Django development server serves the static files itself. On a production server, DEBUG is off, and the files need to come from the web server: set STATIC_ROOT, run python manage.py collectstatic, and configure Nginx or Apache so the STATIC_URL address points to that directory. After that, the styling and the Django admin load as usual, and faster.

How do I move data from one Django project to another?

The python manage.py dumpdata command saves the data to a JSON file, and python manage.py loaddata loads it into the new database after you run migrate on it. It's best to add the --natural-foreign and --natural-primary options and leave out contenttypes and auth.Permission, which Django creates on its own. This way you can move data even between different types of databases, for example from SQLite to PostgreSQL.

Can I run a Django site on a VPS?

Yes. A Python VPS comes with Python, pip, and venv preinstalled, and you get full root access over SSH. You install Django and Gunicorn or Uvicorn in a virtual environment, connect a database such as PostgreSQL or MySQL, run the site as a systemd service, and set up a web server in front of it. All the settings stay fully under your control, and several projects can run on the same server, each in its own environment.

Shopping cart

Your cart is emptyYou can start with one of our popular plans.

Site search

Accessibility

Text size
100%
Accessibility statement