Deployment checklistLink to this heading
The internet is a hostile environment. Before deploying your Django project, you should take some time to review your settings, with security, performance, and operations in mind.
Django includes many security features. Some are built-in and always enabled. Others are optional because they aren’t always appropriate, or because they’re inconvenient for development. For example, forcing HTTPS may not be suitable for all websites, and it’s impractical for local development.
Performance optimizations are another category of trade-offs with convenience. For instance, caching is useful in production, less so for local development. Error reporting needs are also widely different.
The following checklist includes settings that:
must be set properly for Django to provide the expected level of security;
are expected to be different in each environment;
habilitar funciones de seguridad opcionales;
habilitar optimizaciones de rendimiento;
provide error reporting.
Many of these settings are sensitive and should be treated as confidential. If you’re releasing the source code for your project, a common practice is to publish suitable settings for development, and to use a private settings module for production.
Ejecute manage.py check --deployLink to this heading
Some of the checks described below can be automated using the check
--deploy option. Be sure to run it against your production settings file as
described in the option’s documentation.
Critical settingsLink to this heading
SECRET_KEYLink to this heading
The secret key must be a large random value and it must be kept secret.
Asegúrese de que la clave utilizada en producción no se use en ningún otro lugar y evite enviarla al control de código fuente. Esto reduce la cantidad de vectores desde los cuales un atacante puede adquirir la clave.
En lugar de codificar la clave secreta en su módulo de configuración, considere cargarla desde una variable de entorno:
import os
SECRET_KEY = os.environ["SECRET_KEY"]
or from a file:
with open("/etc/secret_key.txt") as f:
SECRET_KEY = f.read().strip()
If rotating secret keys, you may use SECRET_KEY_FALLBACKS:
import os
SECRET_KEY = os.environ["CURRENT_SECRET_KEY"]
SECRET_KEY_FALLBACKS = [
os.environ["OLD_SECRET_KEY"],
]
Ensure that old secret keys are removed from SECRET_KEY_FALLBACKS in a
timely manner.
DEBUGLink to this heading
You must never enable debug in production.
You’re certainly developing your project with DEBUG = True,
since this enables handy features like full tracebacks in your browser.
For a production environment, though, this is a really bad idea, because it leaks lots of information about your project: excerpts of your source code, local variables, settings, libraries used, etc.
Environment-specific settingsLink to this heading
ALLOWED_HOSTSLink to this heading
When DEBUG = False, Django doesn’t work at all without a
suitable value for ALLOWED_HOSTS.
This setting is required to protect your site against some CSRF attacks. If
you use a wildcard, you must perform your own validation of the Host HTTP
header, or otherwise ensure that you aren’t vulnerable to this category of
attacks.
You should also configure the web server that sits in front of Django to validate the host. It should respond with a static error page or ignore requests for incorrect hosts instead of forwarding the request to Django. This way you’ll avoid spurious errors in your Django logs (or emails if you have error reporting configured that way). For example, on nginx you might set up a default server to return «444 No Response» on an unrecognized host:
server {
listen 80 default_server;
return 444;
}
CACHESLink to this heading
If you’re using a cache, connection parameters may be different in development and in production. Django defaults to per-process local-memory caching which may not be desirable.
Cache servers often have weak authentication. Make sure they only accept connections from your application servers.
DATABASESLink to this heading
Database connection parameters are probably different in development and in production.
Database passwords are very sensitive. You should protect them exactly like
SECRET_KEY.
For maximum security, make sure database servers only accept connections from your application servers.
If you haven’t set up backups for your database, do it right now!
STATIC_ROOT and STATIC_URLLink to this heading
Static files are automatically served by the development server. In
production, you must define a STATIC_ROOT directory where
collectstatic will copy them.
See How to manage static files (e.g. images, JavaScript, CSS) for more information.
MEDIA_ROOT and MEDIA_URLLink to this heading
Media files are uploaded by your users. They’re untrusted! Make sure your web
server never attempts to interpret them. For instance, if a user uploads a
.php file, the web server shouldn’t execute it.
Now is a good time to check your backup strategy for these files.
HTTPSLink to this heading
Any website which allows users to log in should enforce site-wide HTTPS to avoid transmitting access tokens in clear. In Django, access tokens include the login/password, the session cookie, and password reset tokens. (You can’t do much to protect password reset tokens if you’re sending them by email.)
Protecting sensitive areas such as the user account or the admin isn’t sufficient, because the same session cookie is used for HTTP and HTTPS. Your web server must redirect all HTTP traffic to HTTPS, and only transmit HTTPS requests to Django.
Once you’ve set up HTTPS, enable the following settings.
Performance optimizationsLink to this heading
Setting DEBUG = False disables several features that are
only useful in development. In addition, you can tune the following settings.
SesionesLink to this heading
Consider using cached sessions to improve performance.
If using database-backed sessions, regularly clear old sessions to avoid storing unnecessary data.
CONN_MAX_AGELink to this heading
Enabling persistent database connections can result in a nice speed-up when connecting to the database accounts for a significant part of the request processing time.
This helps a lot on virtualized hosts with limited network performance.
TEMPLATESLink to this heading
Enabling the cached template loader often improves performance drastically, as
it avoids compiling each template every time it needs to be rendered. When
DEBUG = False, the cached template loader is enabled
automatically. See django.template.loaders.cached.Loader for more
information.
Error reportingLink to this heading
By the time you push your code to production, it’s hopefully robust, but you can’t rule out unexpected errors. Thankfully, Django can capture errors and notify you accordingly.
LOGGINGLink to this heading
Review your logging configuration before putting your website in production, and check that it works as expected as soon as you have received some traffic.
See Logging for details on logging.
ADMINS and MANAGERSLink to this heading
ADMINS will be notified of 500 errors by email.
MANAGERS will be notified of 404 errors.
IGNORABLE_404_URLS can help filter out spurious reports.
See How to manage error reporting for details on error reporting by email.
Customize the default error viewsLink to this heading
Django includes default views and templates for several HTTP error codes. You
may want to override the default templates by creating the following templates
in your root template directory: 404.html, 500.html, 403.html, and
400.html. The default error views that use these
templates should suffice for 99% of web applications, but you can
customize them as well.