File: README.md
Cookiecutter Django
Powered by Cookiecutter, Cookiecutter Django is a framework for jumpstarting
production-ready Django projects quickly.
- Documentation: https://cookiecutter-django.readthedocs.io/en/latest/
- See Troubleshooting for common errors and obstacles
- If you have problems with Cookiecutter Django, please open issues don't send
emails to the maintainers.
Features
- For Django 6.0
- Works with Python 3.14
- Renders Django projects with 100% starting test coverage
- Twitter Bootstrap v5
- 12-Factor based settings via django-environ
- Secure by default. We believe in SSL.
- Optimized development and production settings
- Registration via django-allauth
- Comes with custom user model ready to go
- Optional basic ASGI setup for Websockets
- Optional custom static build using Gulp or Webpack
- Send emails via Anymail (using Mailgun by default or Amazon SES if AWS is selected cloud provider, but switchable)
- Media storage using Amazon S3, Google Cloud Storage, Azure Storage or nginx
- Docker support using docker-compose for development and production (using Traefik with LetsEncrypt support)
- Procfile for deploying to Heroku
- Instructions for deploying to PythonAnywhere
- Run tests with unittest or pytest
- Customizable PostgreSQL version
- Default integration with pre-commit for identifying simple issues before submission to code review
Optional Integrations
These features can be enabled during initial project setup.
- Serve static files from Amazon S3, Google Cloud Storage, Azure Storage or Whitenoise
- Configuration for Celery and Flower (the latter in Docker setup only)
- Integration with Mailpit or Mailtrap Local for local email testing
- Integration with Sentry for error logging
Constraints
- Only maintained 3rd party libraries are used.
- Uses PostgreSQL everywhere: 14 - 18 (MySQL fork also available).
- Environment variables for configuration (This won't work with Apache/mod_wsgi).
Support this Project!
This project is an open source project run by volunteers. You can sponsor us via OpenCollective or individually via GitHub Sponsors:
- Daniel Roy Greenfeld, Project Lead (GitHub, Patreon): expertise in Django and AWS ELB.
- Fabio C. Barrionuevo, Core Developer (GitHub): expertise in Python/Django, hands-on DevOps and frontend experience.
- Bruno Alla, Core Developer (GitHub): expertise in Python/Django and DevOps.
- Nikita Shupeyko, Core Developer (GitHub): expertise in Python/Django, hands-on DevOps and frontend experience.
Projects that provide financial support to the maintainers:
Two Scoops of Django
Two Scoops of Django 3.x is the best ice cream-themed Django reference in the universe!
PyUp
PyUp brings you automated security and dependency updates used by Google and other organizations. Free for open source projects!
Usage
Let's pretend you want to create a Django project called "redditclone". Rather than using startproject
and then editing the results to include your name, email, and various configuration issues that always get forgotten until the worst possible moment, get cookiecutter to do all the work.
First, get Cookiecutter. Trust me, it's awesome:
uv tool install "cookiecutter>=1.7.0"Now run it against this repo:
uvx cookiecutter https://github.com/cookiecutter/cookiecutter-djangoYou'll be prompted for some values. Provide them, then a Django project will be created for you.
Warning: After this point, change 'Daniel Greenfeld', 'pydanny', etc to your own information.
Answer the prompts with your own desired options. For example:
Cloning into 'cookiecutter-django'...
remote: Counting objects: 550, done.
remote: Compressing objects: 100% (310/310), done.
remote: Total 550 (delta 283), reused 479 (delta 222)
Receiving objects: 100% (550/550), 127.66 KiB | 58 KiB/s, done.
Resolving deltas: 100% (283/283), done.
project_name [My Awesome Project]: Reddit Clone
project_slug [reddit_clone]: reddit
description [Behold My Awesome Project!]: A reddit clone.
author_name [Daniel Roy Greenfeld]: Daniel Greenfeld
domain_name [example.com]: myreddit.com
email [[email protected]]: [email protected]
version [0.1.0]: 0.0.1
Select open_source_license:
1 - MIT
2 - BSD
3 - GPLv3
4 - Apache Software License 2.0
5 - Not open source
Choose from 1, 2, 3, 4, 5 [1]: 1
Select username_type:
1 - username
2 - email
Choose from 1, 2 [1]: 1
timezone [UTC]: America/Los_Angeles
windows [n]: n
Select an editor to use. The choices are:
1 - None
2 - PyCharm
3 - VS Code
Choose from 1, 2, 3 [1]: 1
use_docker [n]: n
Select postgresql_version:
1 - 18
2 - 17
3 - 16
4 - 15
5 - 14
Choose from 1, 2, 3, 4 [1]: 1
Select cloud_provider:
1 - AWS
2 - GCP
3 - None
Choose from 1, 2, 3 [1]: 1
Select mail_service:
1 - Mailgun
2 - Amazon SES
3 - Mailjet
4 - Mandrill
5 - Postmark
6 - Sendgrid
7 - Brevo (formerly SendinBlue)
8 - SparkPost
9 - Other SMTP
Choose from 1, 2, 3, 4, 5, 6, 7, 8, 9 [1]: 1
Select rest_api [None]:
1 - None
2 - DRF
3 - Django Ninja
Choose from 1, 2, 3 [1]: 1
use_async [n]: n
Select frontend_pipeline:
1 - None
2 - Django Compressor
3 - Gulp
4 - Webpack
Choose from 1, 2, 3, 4 [1]: 1
use_celery [n]: y
Select mail_catcher:
1 - None
2 - Mailpit
3 - Mailtrap Local
Choose from 1, 2, 3 [1]: 1
use_sentry [n]: y
use_whitenoise [n]: n
use_heroku [n]: y
Select ci_tool:
1 - None
2 - Travis
3 - Gitlab
4 - Github
Choose from 1, 2, 3, 4 [1]: 4
keep_local_envs_in_vcs [y]: y
debug [n]: nEnter the project and take a look around:
cd reddit/
lsCreate a git repo and push it there:
git init
git add .
git commit -m "first awesome commit"
git remote add origin [email protected]:pydanny/redditclone.git
git push -u origin mainNow take a look at your repo. Don't forget to carefully look at the generated README. Awesome, right?
For local development, see the following:
Community
- Have questions? Before you ask questions anywhere else, please post your question on Stack Overflow under the cookiecutter-django tag. We check there periodically for questions.
- If you think you found a bug or want to request a feature, please open an issue.
- For anything else, you can chat with us on Discord.
For Readers of Two Scoops of Django
You may notice that some elements of this project do not exactly match what we describe in chapter 3. The reason for that is this project, amongst other things, serves as a test bed for trying out new ideas and concepts. Sometimes they work, sometimes they don't, but the end result is that it won't necessarily match precisely what is described in the book I co-authored.
For PyUp Users
If you are using PyUp to keep your dependencies updated and secure, use the code cookiecutter during checkout to get 15% off every month.
"Your Stuff"
Scattered throughout the Python and HTML of this project are places marked with "your stuff". This is where third-party libraries are to be integrated with your project.
For MySQL users
To get full MySQL support in addition to the default Postgresql, you can use this fork of the cookiecutter-django:
https://github.com/mabdullahadeel/cookiecutter-django-mysql
Releases
Need a stable release? You can find them at https://github.com/cookiecutter/cookiecutter-django/releases
Not Exactly What You Want?
This is what I want. It might not be what you want. Don't worry, you have options:
Fork This
If you have differences in your preferred setup, I encourage you to fork this to create your own version.
Once you have your fork working, let me know and I'll add it to a 'Similar Cookiecutter Templates' list here.
It's up to you whether to rename your fork.
If you do rename your fork, I encourage you to submit it to the following places:
- cookiecutter so it gets listed in the README as a template.
- The cookiecutter grid on Django Packages.
Submit a Pull Request
We accept pull requests if they're small, atomic, and make our own project development
experience better.
Articles
- Why cookiecutter-django is Essential for Your Next Django Project - Aug. 4, 2024
- How to Make Your Own Django Cookiecutter Template! - Aug. 10, 2023
- Cookiecutter Django With Amazon RDS - Apr, 2, 2021
- Complete Walkthrough: Blue/Green Deployment to AWS ECS using GitHub actions - June 10, 2020
- Using cookiecutter-django with Google Cloud Storage - Mar. 12, 2019
- cookiecutter-django with Nginx, Route 53 and ELB - Feb. 12, 2018
- cookiecutter-django and Amazon RDS - Feb. 7, 2018
- Using Cookiecutter to Jumpstart a Django Project on Windows with PyCharm - May 19, 2017
- Exploring with Cookiecutter - Dec. 3, 2016
- Introduction to Cookiecutter-Django - Feb. 19, 2016
- Django and GitLab - Running Continuous Integration and tests with your FREE account - May. 11, 2016
- Development and Deployment of Cookiecutter-Django on Fedora - Jan. 18, 2016
- Development and Deployment of Cookiecutter-Django via Docker - Dec. 29, 2015
- How to create a Django Application using Cookiecutter and Django 1.8 - Sept. 12, 2015
Have a blog or online publication? Write about your cookiecutter-django tips and tricks, then send us a pull request with the link.
File: {{cookiecutter.project_slug}}/docs/pycharm/configuration.rst
Docker Remote Debugging
To connect to python remote interpreter inside docker, you have to make sure first, that Pycharm is aware of your docker.
Go to Settings > Build, Execution, Deployment > Docker. If you are on linux, you can use docker directly using its socket unix:///var/run/docker.sock, if you are on Windows or Mac, make sure that you have docker-machine installed, then you can simply Import credentials from Docker Machine.
.. image:: images/1.png
Configure Remote Python Interpreter
This repository comes with already prepared "Run/Debug Configurations" for docker.
.. image:: images/2.png
But as you can see, at the beginning there is something wrong with them. They have red X on django icon, and they cannot be used, without configuring remote python interpreter. To do that, you have to go to Settings > Build, Execution, Deployment first.
Next, you have to add new remote python interpreter, based on already tested deployment settings. Go to Settings > Project > Project Interpreter. Click on the cog icon, and click Add Remote.
.. image:: images/3.png
Switch to Docker Compose and select docker-compose.local.yml file from directory of your project, next set Service name to django
.. image:: images/4.png
Having that, click OK. Close Settings panel, and wait few seconds...
.. image:: images/7.png
After few seconds, all Run/Debug Configurations should be ready to use.
.. image:: images/8.png
Things you can do with provided configuration:
- run and debug python code
.. image:: images/f1.png
- run and debug tests
.. image:: images/f2.png
.. image:: images/f3.png
- run and debug migrations or different django management commands
.. image:: images/f4.png
- and many others..
Known issues
- Pycharm hangs on "Connecting to Debugger"
.. image:: images/issue1.png
This might be fault of your firewall. Take a look on this ticket - https://youtrack.jetbrains.com/issue/PY-18913
- Modified files in
.ideadirectory
Most of the files from .idea/ were added to .gitignore with a few exceptions, which were made, to provide "ready to go" configuration. After adding remote interpreter some of these files are altered by PyCharm:
.. image:: images/issue2.png
In theory you can remove them from repository, but then, other people will lose a ability to initialize a project from provided configurations as you did. To get rid of this annoying state, you can run command::
$ git update-index --assume-unchanged {{cookiecutter.project_slug}}.imlFile: {{cookiecutter.project_slug}}/docs/howto.rst
How To - Project Documentation
Get Started
Documentation can be written as rst files in {{cookiecutter.project_slug}}/docs.
{% if cookiecutter.use_docker == 'n' %}
To build and serve docs, use the command::
uv run make livehtmlfrom inside the {{cookiecutter.project_slug}}/docs directory.
{% else %}
To build and serve docs, use the commands::
docker compose -f docker-compose.docs.yml up{% endif %}
Changes to files in docs/_source will be picked up and reloaded automatically.
Sphinx <https://www.sphinx-doc.org/>_ is the tool used to build documentation.
Docstrings to Documentation
The sphinx extension apidoc <https://www.sphinx-doc.org/en/master/man/sphinx-apidoc.html>_ is used to automatically document code using signatures and docstrings.
Numpy or Google style docstrings will be picked up from project files and available for documentation. See the Napoleon <https://sphinxcontrib-napoleon.readthedocs.io/en/latest/>_ extension for details.
For an in-use example, see the page source <_sources/users.rst.txt>_ for :ref:users.
To compile all docstrings automatically into documentation source files, use the command:
::
uv run make apidocs{% if cookiecutter.use_docker == 'y' %}
This can be done in the docker container:
::
docker run --rm docs make apidocs{% endif -%}
File: {{cookiecutter.project_slug}}/docs/index.rst
.. {{ cookiecutter.project_name }} documentation master file, created by
sphinx-quickstart.
You can adapt this file completely to your liking, but it should at least
contain the root toctree directive.
Welcome to {{ cookiecutter.project_name }}'s documentation!
.. toctree::
:maxdepth: 2
:caption: Contents:
howto{% if cookiecutter.editor == 'PyCharm' %}
pycharm/configuration{% endif %}
users
Indices and tables
- :ref:
genindex - :ref:
modindex - :ref:
search
File: {{cookiecutter.project_slug}}/docs/users.rst
.. _users:
Users
Starting a new project, itโs highly recommended to set up a custom user model,
even if the default User model is sufficient for you.
This model behaves identically to the default user model,
but youโll be able to customize it in the future if the need arises.
.. automodule:: {{cookiecutter.project_slug}}.users.models
:members:
:noindex:
File: {{cookiecutter.project_slug}}/locale/README.md
Translations
Start by configuring the LANGUAGES settings in base.py, by uncommenting languages you are willing to support. Then, translation strings will be placed in this folder when running:
{% if cookiecutter.use_docker == 'y' %}docker compose -f docker-compose.local.yml run --rm django {% endif %}python manage.py makemessages --all --no-locationThis should generate django.po (stands for Portable Object) files under each locale <locale name>/LC_MESSAGES/django.po. Each translatable string in the codebase is collected with its msgid and need to be translated as msgstr, for example:
msgid "users"
msgstr "utilisateurs"Once all translations are done, they need to be compiled into .mo files (stands for Machine Object), which are the actual binary files used by the application:
{% if cookiecutter.use_docker == 'y' %}docker compose -f docker-compose.local.yml run --rm django {% endif %}python manage.py compilemessagesNote that the .po files are NOT used by the application directly, so if the .mo files are out of date, the content won't appear as translated even if the .po files are up-to-date.
Production
The production image runs compilemessages automatically at build time, so as long as your translated source files (PO) are up-to-date, you're good to go.
Add a new language
- Update the
LANGUAGESsetting to your project's base settings. - Create the locale folder for the language next to this file, e.g.
fr_FRfor French. Make sure the case is correct. - Run
makemessages(as instructed above) to generate the PO files for the new language.
File: {{cookiecutter.project_slug}}/README.md
{{cookiecutter.project_name}}
{{ cookiecutter.description }}
{%- if cookiecutter.open_source_license != "Not open source" %}
License: {{cookiecutter.open_source_license}}
{%- endif %}
Settings
Moved to settings.
Basic Commands
Setting Up Your Users
To create a normal user account, just go to Sign Up and fill out the form. Once you submit it, you'll see a "Verify Your E-mail Address" page. Go to your console to see a simulated email verification message. Copy the link into your browser. Now the user's email should be verified and ready to go.
To create a superuser account, use this command:
textuv run python manage.py createsuperuser
For convenience, you can keep your normal user logged in on Chrome and your superuser logged in on Firefox (or similar), so that you can see how the site behaves for both kinds of users.
Type checks
Running type checks with mypy:
uv run mypy {{cookiecutter.project_slug}}Test coverage
To run the tests, check your test coverage, and generate an HTML coverage report:
uv run coverage run -m pytest
uv run coverage html
uv run open htmlcov/index.htmlRunning tests with pytest
uv run pytestLive reloading and Sass CSS compilation
Moved to Live reloading and SASS compilation.
{%- if cookiecutter.use_celery == "y" %}
Celery
This app comes with Celery.
To run a celery worker:
cd {{cookiecutter.project_slug}}
uv run celery -A config.celery_app worker -l infoPlease note: For Celery's import magic to work, it is important where the celery commands are run. If you are in the same folder with manage.py, you should be right.
To run periodic tasks, you'll need to start the celery beat scheduler service. You can start it as a standalone process:
cd {{cookiecutter.project_slug}}
uv run celery -A config.celery_app beator you can embed the beat service inside a worker with the -B option (not recommended for production use):
cd {{cookiecutter.project_slug}}
uv run celery -A config.celery_app worker -B -l info{%- endif %}
{%- if cookiecutter.mail_catcher == "Mailpit" %}
Email Server
{%- if cookiecutter.use_docker == "y" %}
In development, it is often nice to be able to see emails that are being sent from your application. For that reason local SMTP server Mailpit with a web interface is available as docker container.
Container mailpit will start automatically when you will run all docker containers.
Please check cookiecutter-django Docker documentation for more details how to start all containers.
With Mailpit running, to view messages that are sent by your application, open your browser and go to http://127.0.0.1:8025
{%- else %}
In development, it is often nice to be able to see emails that are being sent from your application. If you choose to use Mailpit when generating the project a local SMTP server with a web interface will be available.
Download the latest Mailpit release for your OS.
Copy the binary file to the project root.
Make it executable:
textchmod +x mailpitSpin up another terminal window and start it there:
text./mailpitCheck out http://127.0.0.1:8025/ to see how it goes.
Now you have your own mail server running locally, ready to receive whatever you send it.
{%- endif %}
{%- endif %}
{%- if cookiecutter.mail_catcher == "Mailtrap Local" %}
Email Server
{%- if cookiecutter.use_docker == "y" %}
In development, it is often nice to be able to see emails that are being sent from your application. For that reason local SMTP server Mailtrap Local with a web interface is available as docker container.
Container mailtrap-local will start automatically when you will run all docker containers.
Please check cookiecutter-django Docker documentation for more details how to start all containers.
With Mailtrap Local running, to view messages that are sent by your application, open your browser and go to http://127.0.0.1:3550
{%- else %}
In development, it is often nice to be able to see emails that are being sent from your application. If you choose to use Mailtrap Local when generating the project a local SMTP server with a web interface will be available.
Download the latest Mailtrap Local release for your OS.
Copy the binary file to the project root.
Make it executable:
textchmod +x mailtrap-localSpin up another terminal window and start it there:
text./mailtrap-localCheck out http://127.0.0.1:3550/ to see how it goes.
Now you have your own mail server running locally, ready to receive whatever you send it.
{%- endif %}
{%- endif %}
{%- if cookiecutter.use_sentry == "y" %}
Sentry
Sentry is an error logging aggregator service. You can sign up for a free account at https://sentry.io/signup/?code=cookiecutter or download and host it yourself.
The system is set up with reasonable defaults, including 404 logging and integration with the WSGI application.
You must set the DSN url in production.
{%- endif %}
Deployment
The following details how to deploy this application.
{%- if cookiecutter.use_heroku.lower() == "y" %}
Heroku
See detailed cookiecutter-django Heroku documentation.
{%- endif %}
{%- if cookiecutter.use_docker.lower() == "y" %}
Docker
See detailed cookiecutter-django Docker documentation.
{%- endif %}
{%- if cookiecutter.frontend_pipeline in ['Gulp', 'Webpack'] %}
Custom Bootstrap Compilation
The generated CSS is set up with automatic Bootstrap recompilation with variables of your choice.
Bootstrap v5 is installed using npm and customised by tweaking your variables in static/sass/custom_bootstrap_vars.
You can find a list of available variables in the bootstrap source, or get explanations on them in the Bootstrap docs.
Bootstrap's javascript as well as its dependencies are concatenated into a single file: static/js/vendors.js.
{%- endif %}
File: docs/1-getting-started/project-generation-options.rst
.. _template-options:
Project Generation Options
This page describes all the template options that will be prompted by the cookiecutter CLI_ prior to generating your project.
.. _cookiecutter CLI: https://github.com/cookiecutter/cookiecutter
project_name:
Your project's human-readable name, capitals and spaces allowed.
project_slug:
Your project's slug without dashes or spaces. Used to name your repo
and in other places where a Python-importable version of your project name
is needed.
Describes your project and gets used in places like README.rst and such.
author_name:
This is you! The value goes into places like LICENSE and such.
email:
The email address you want to identify yourself in the project.
username_type:
The type of username you want to use in the project. This can be either
username or email. If you choose username, the email field
will be included. If you choose email, the username field will be
excluded. It is best practice to always include an email field, so there is
no option for having just the username field.
domain_name:
The domain name you plan to use for your project once it goes live.
Note that it can be safely changed later on whenever you need to.
version:
The version of the project at its inception.
open_source_license:
A software license for the project. The choices are:
1. MIT_
2. BSD_
3. GPLv3_
4. `Apache Software License 2.0`_
5. Not open sourcetimezone:
The value to be used for the TIME_ZONE setting of the project.
windows:
Indicates whether the project should be configured for development on Windows.
editor:
Select an editor to use. The choices are:
1. None
2. PyCharm_
3. `VS Code`_use_docker:
Indicates whether the project should be configured to use Docker_, Docker Compose_ and devcontainer_.
postgresql_version:
Select a PostgreSQL_ version to use. The choices are:
1. 18
2. 17
3. 16
4. 15
5. 14cloud_provider:
Select a cloud provider for static & media files. The choices are:
1. AWS_
2. GCP_
3. Azure_
4. None
If you choose no cloud provider and docker, the production stack will serve the media files via an nginx Docker service. Without Docker, the media files won't work.mail_service:
Select an email service that Django-Anymail provides
1. Mailgun_
2. `Amazon SES`_
3. Mailjet_
4. Mandrill_
5. Postmark_
6. SendGrid_
7. `Brevo (formerly SendinBlue)`_
8. SparkPost_
9. `Other SMTP`_rest_api:
Select a REST API framework to use. The choices are:
1. None
2. `Django Rest Framework`_
3. `Django Ninja`_use_async:
Indicates whether the project should use web sockets with Uvicorn + Gunicorn.
frontend_pipeline:
Select a pipeline to compile and optimise frontend assets (JS, CSS, ...):
1. None
2. `Django Compressor`_
3. `Gulp`_
4. `Webpack`_Both Gulp and Webpack support Bootstrap recompilation with real-time variables alteration.
use_celery:
Indicates whether the project should be configured to use Celery_.
mail_catcher:
Select a local email catcher to receive emails during development. The choices are:
1. None
2. Mailpit_
3. `Mailtrap Local`_use_sentry:
Indicates whether the project should be configured to use Sentry_.
use_whitenoise:
Indicates whether the project should be configured to use WhiteNoise_.
use_heroku:
Indicates whether the project should be configured so as to be deployable
to Heroku_.
ci_tool:
Select a CI tool for running tests. The choices are:
1. None
2. `Travis CI`_
3. `Gitlab CI`_
4. `Github Actions`_
5. `Drone CI`_keep_local_envs_in_vcs:
Indicates whether the projectโs .envs/.local/ should be kept in VCS (comes in handy when working in teams where local environment reproducibility is strongly encouraged).
debug:
Indicates whether the project should be configured for debugging.
This option is relevant for Cookiecutter Django developers only.
.. _MIT: https://opensource.org/licenses/MIT
.. _BSD: https://opensource.org/licenses/BSD-3-Clause
.. _GPLv3: https://www.gnu.org/licenses/gpl.html
.. _Apache Software License 2.0: https://www.apache.org/licenses/LICENSE-2.0
.. _PyCharm: https://www.jetbrains.com/pycharm/
.. _VS Code: https://github.com/microsoft/vscode
.. _Docker: https://github.com/docker/docker
.. _Docker Compose: https://docs.docker.com/compose/
.. _devcontainer: https://containers.dev/
.. _PostgreSQL: https://www.postgresql.org/docs/
.. _Gulp: https://github.com/gulpjs/gulp
.. _Webpack: https://webpack.js.org
.. _AWS: https://aws.amazon.com/s3/
.. _GCP: https://cloud.google.com/storage/
.. _Azure: https://azure.microsoft.com/en-us/products/storage/blobs/
.. _Amazon SES: https://aws.amazon.com/ses/
.. _Mailgun: https://www.mailgun.com
.. _Mailjet: https://www.mailjet.com
.. _Mandrill: http://mandrill.com
.. _Postmark: https://postmarkapp.com
.. _SendGrid: https://sendgrid.com
.. _Brevo (formerly SendinBlue): https://www.brevo.com
.. _SparkPost: https://www.sparkpost.com
.. _Other SMTP: https://anymail.readthedocs.io/en/stable/
.. _Django Rest Framework: https://github.com/encode/django-rest-framework/
.. _Django Ninja: https://github.com/vitalik/django-ninja
.. _Django Compressor: https://github.com/django-compressor/django-compressor
.. _Celery: https://github.com/celery/celery
.. _Mailpit: https://github.com/axllent/mailpit
.. _Mailtrap Local: https://github.com/mailtrap/mailtrap-local
.. _Sentry: https://github.com/getsentry/sentry
.. _WhiteNoise: https://github.com/evansd/whitenoise
.. _Heroku: https://github.com/heroku/heroku-buildpack-python
.. _Travis CI: https://travis-ci.org/
.. _GitLab CI: https://docs.gitlab.com/ee/ci/
.. _Drone CI: https://docs.drone.io/pipeline/overview/
.. _Github Actions: https://docs.github.com/en/actions
File: docs/1-getting-started/settings.rst
.. _settings:
Settings
This project relies extensively on environment settings which will not work with Apache/mod_wsgi setups. It has been deployed successfully with both Gunicorn/Nginx and even uWSGI/Nginx.
For configuration purposes, the following table maps environment variables to their Django setting and project settings:
======================================= =========================== ============================================== ======================================================================
Environment Variable Django Setting Development Default Production Default
======================================= =========================== ============================================== ======================================================================
DJANGO_READ_DOT_ENV_FILE READ_DOT_ENV_FILE False False
======================================= =========================== ============================================== ======================================================================
======================================= =========================== ============================================== ======================================================================
Environment Variable Django Setting Development Default Production Default
======================================= =========================== ============================================== ======================================================================
DATABASE_URL DATABASES auto w/ Docker; postgres://project_slug w/o raises error
DJANGO_ADMIN_URL n/a 'admin/' raises error
DJANGO_DEBUG DEBUG True False
DJANGO_SECRET_KEY SECRET_KEY auto-generated raises error
DJANGO_SECURE_SSL_REDIRECT SECURE_SSL_REDIRECT n/a True
DJANGO_SECURE_CONTENT_TYPE_NOSNIFF SECURE_CONTENT_TYPE_NOSNIFF n/a True
DJANGO_SECURE_FRAME_DENY SECURE_FRAME_DENY n/a True
DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS HSTS_INCLUDE_SUBDOMAINS n/a True
DJANGO_SESSION_COOKIE_HTTPONLY SESSION_COOKIE_HTTPONLY n/a True
DJANGO_SESSION_COOKIE_SECURE SESSION_COOKIE_SECURE n/a False
DJANGO_DEFAULT_FROM_EMAIL DEFAULT_FROM_EMAIL n/a "your_project_name <noreply@your_domain_name>"
DJANGO_SERVER_EMAIL SERVER_EMAIL n/a "your_project_name <noreply@your_domain_name>"
DJANGO_EMAIL_SUBJECT_PREFIX EMAIL_SUBJECT_PREFIX n/a "[your_project_name] "
DJANGO_ALLOWED_HOSTS ALLOWED_HOSTS ['*'] ['your_domain_name']
======================================= =========================== ============================================== ======================================================================
The following table lists settings and their defaults for third-party applications, which may or may not be part of your project:
======================================= =========================== ============================================== ======================================================================
Environment Variable Django Setting Development Default Production Default
======================================= =========================== ============================================== ======================================================================
DJANGO_AWS_ACCESS_KEY_ID AWS_ACCESS_KEY_ID n/a raises error
DJANGO_AWS_SECRET_ACCESS_KEY AWS_SECRET_ACCESS_KEY n/a raises error
DJANGO_AWS_STORAGE_BUCKET_NAME AWS_STORAGE_BUCKET_NAME n/a raises error
DJANGO_AWS_S3_REGION_NAME AWS_S3_REGION_NAME n/a None
DJANGO_AWS_S3_CUSTOM_DOMAIN AWS_S3_CUSTOM_DOMAIN n/a None
DJANGO_AWS_S3_MAX_MEMORY_SIZE AWS_S3_MAX_MEMORY_SIZE n/a 100_000_000
DJANGO_GCP_STORAGE_BUCKET_NAME GS_BUCKET_NAME n/a raises error
GOOGLE_APPLICATION_CREDENTIALS n/a n/a raises error
DJANGO_AZURE_ACCOUNT_KEY AZURE_ACCOUNT_KEY n/a raises error
DJANGO_AZURE_ACCOUNT_NAME AZURE_ACCOUNT_NAME n/a raises error
DJANGO_AZURE_CONTAINER_NAME AZURE_CONTAINER n/a raises error
SENTRY_DSN SENTRY_DSN n/a raises error
SENTRY_ENVIRONMENT n/a n/a production
SENTRY_TRACES_SAMPLE_RATE n/a n/a 0.0
DJANGO_SENTRY_LOG_LEVEL SENTRY_LOG_LEVEL n/a logging.INFO
MAILGUN_API_KEY MAILGUN_API_KEY n/a raises error
MAILGUN_DOMAIN MAILGUN_SENDER_DOMAIN n/a raises error
MAILGUN_API_URL n/a n/a "https://api.mailgun.net/v3"
MAILJET_API_KEY MAILJET_API_KEY n/a raises error
MAILJET_SECRET_KEY MAILJET_SECRET_KEY n/a raises error
MAILJET_API_URL n/a n/a "https://api.mailjet.com/v3"
MANDRILL_API_KEY MANDRILL_API_KEY n/a raises error
MANDRILL_API_URL n/a n/a "https://mandrillapp.com/api/1.0"
POSTMARK_SERVER_TOKEN POSTMARK_SERVER_TOKEN n/a raises error
POSTMARK_API_URL n/a n/a "https://api.postmarkapp.com/"
SENDGRID_API_KEY SENDGRID_API_KEY n/a raises error
SENDGRID_GENERATE_MESSAGE_ID True n/a raises error
SENDGRID_MERGE_FIELD_FORMAT None n/a raises error
SENDGRID_API_URL n/a n/a "https://api.sendgrid.com/v3/"
BREVO_API_KEY BREVO_API_KEY n/a raises error
BREVO_API_URL n/a n/a "https://api.brevo.com/v3/"
SPARKPOST_API_KEY SPARKPOST_API_KEY n/a raises error
SPARKPOST_API_URL n/a n/a "https://api.sparkpost.com/api/v1"
======================================= =========================== ============================================== ======================================================================
Other Environment Settings
DJANGO_ACCOUNT_ALLOW_REGISTRATION (=True)
Allow enable or disable user registration through django-allauth without disabling other characteristics like authentication and account management. (Django Setting: ACCOUNT_ALLOW_REGISTRATION)
DJANGO_ADMIN_FORCE_ALLAUTH (=False)
Force the admin sign in process to go through the django-allauth workflow.
File: docs/2-local-development/developing-locally.rst
Getting Up and Running Locally
.. index:: PostgreSQL
Setting Up Development Environment
Make sure to have the following on your host:
- uv https://docs.astral.sh/uv/getting-started/installation/
- PostgreSQL_.
- Redis_, if using Celery
- Cookiecutter_
#. .. include:: generate-project-block.rst
#. Install development requirements: ::
cd <what you have entered as the project_slug at setup stage>
uv sync
git init # A git repo is required for pre-commit to install
uv run pre-commit install.. note::
the `pre-commit` hook exists in the generated project as default.
For the details of `pre-commit`, follow the `pre-commit`_ site.#. Create a new PostgreSQL database using createdb_: ::
createdb --username=postgres project_slug is what you have entered as the project_slug at the setup stage.
.. note::
if this is the first time a database is created on your machine you might need an
`initial PostgreSQL set up`_ to allow local connections & set a password for
the ``postgres`` user. The `postgres documentation`_ explains the syntax of the config file
that you need to change.#. Set the environment variables for your database(s): ::
export POSTGRES_USER=postgres
export POSTGRES_PASSWORD=
export POSTGRES_DB=<DB name given to createdb>.. note::
Check out the :ref:`settings` page for a comprehensive list of the environments variables... seealso::
To help setting up your environment variables, you have a few options:
* create an ``.env`` file in the root of your project and define all the variables you need in it.
Then you just need to have ``DJANGO_READ_DOT_ENV_FILE=True`` in your machine and all the variables
will be read.
* Use a local environment manager like `direnv`_#. Apply migrations: ::
uv run python manage.py migrate#. If you're running synchronously, see the application being served through Django development server: ::
uv run python manage.py runserver 0.0.0.0:8000or if you're running asynchronously: ::
uv run uvicorn config.asgi:application --host 0.0.0.0 --reload --reload-include '*.html' If you've opted for Webpack or Gulp as frontend pipeline, please see the :ref:dedicated section below.
.. _PostgreSQL: https://www.postgresql.org/download/
.. _Redis: https://redis.io/download
.. _CookieCutter: https://github.com/cookiecutter/cookiecutter
.. _createdb: https://www.postgresql.org/docs/current/static/app-createdb.html
.. _initial PostgreSQL set up: https://web.archive.org/web/20190303010033/http://suite.opengeo.org/docs/latest/dataadmin/pgGettingStarted/firstconnect.html
.. _postgres documentation: https://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html
.. _pre-commit: https://pre-commit.com/
.. _direnv: https://direnv.net/
Creating Your First Django App
After setting up your environment, you're ready to add your first app. This project uses the setup from "Two Scoops of Django" with a two-tier layout:
- Top Level Repository Root has config files, documentation,
manage.py, and more. - Second Level Django Project Root is where your Django apps live.
- Second Level Configuration Root holds settings and URL configurations.
The project layout looks something like this: ::
<repository_root>/
โโโ config/
โ โโโ settings/
โ โ โโโ __init__.py
โ โ โโโ base.py
โ โ โโโ local.py
โ โ โโโ production.py
โ โโโ urls.py
โ โโโ wsgi.py
โโโ <django_project_root>/
โ โโโ <name_of_the_app>/
โ โ โโโ migrations/
โ โ โโโ admin.py
โ โ โโโ apps.py
โ โ โโโ models.py
โ โ โโโ tests.py
โ โ โโโ views.py
โ โโโ __init__.py
โ โโโ ...
โโโ requirements/
โ โโโ base.txt
โ โโโ local.txt
โ โโโ production.txt
โโโ manage.py
โโโ README.md
โโโ ...Following this structured approach, here's how to add a new app:
#. Create the app using Django's startapp command, replacing <name-of-the-app> with your desired app name: ::
uv run python manage.py startapp <name-of-the-app>#. Move the app to the Django Project Root, maintaining the project's two-tier structure: ::
mv <name-of-the-app> <django_project_root>/#. Edit the app's apps.py change name = '<name-of-the-app>' to name = '<django_project_root>.<name-of-the-app>'.
#. Register the new app by adding it to the LOCAL_APPS list in config/settings/base.py, integrating it as an official component of your project.
Setup Email Backend
Mail catcher
During local development it is useful to see the emails your project sends instead of delivering them for real. A mail catcher is a local SMTP server that accepts those emails and shows them in a web interface. For instance, one of the packages we depend upon, ``django-allauth``, sends verification emails to new users signing up as well as to the existing ones who have not yet verified themselves.
Mailpit
"""""""
.. note:: In order for the project to support Mailpit_ it must have been bootstrapped with ``mail_catcher`` set to ``Mailpit``.
Mailpit is written in Go and has no external dependencies.
#. `Download the latest Mailpit release`_ for your OS.
#. Copy the binary file to the project root.
#. Make it executable: ::
chmod +x mailpit
#. Spin up another terminal window and start it there: ::
./mailpit
#. Check out `<http://127.0.0.1:8025/>`_ to see how it goes.
Now you have your own mail server running locally, ready to receive whatever you send it.
.. _`Download the latest Mailpit release`: https://github.com/axllent/mailpit
Mailtrap Local
""""""""""""""
.. note:: In order for the project to support `Mailtrap Local`_ it must have been bootstrapped with ``mail_catcher`` set to ``Mailtrap Local``.
Mailtrap Local is a single self-contained Go binary with no external dependencies and is distributed under the MIT license.
#. `Download the latest Mailtrap Local release`_ for your OS.
#. Copy the binary file to the project root.
#. Make it executable: ::
chmod +x mailtrap-local
#. Spin up another terminal window and start it there: ::
./mailtrap-local
#. Check out `<http://127.0.0.1:3550/>`_ to see how it goes.
Now you have your own mail server running locally, ready to receive whatever you send it.
.. _`Download the latest Mailtrap Local release`: https://github.com/mailtrap/mailtrap-local
Console
~~~~~~~
.. note:: If you have generated your project with ``mail_catcher`` set to ``None`` this will be a default setup.
Alternatively, deliver emails over console via ``EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'``.
In production, we have Mailgun_ configured to have your back!
.. _Mailgun: https://www.mailgun.com/
Celery
------
If the project is configured to use Celery as a task scheduler then, by default, tasks are set to run on the main thread when developing locally instead of getting sent to a broker. However, if you have Redis setup on your local machine, you can set the following in ``config/settings/local.py``::
CELERY_TASK_ALWAYS_EAGER = False
Next, make sure `redis-server` is installed (per the `Getting started with Redis`_ guide) and run the server in one terminal::
redis-server
Start the Celery worker by running the following command in another terminal::
uv run celery -A config.celery_app worker --loglevel=info
That Celery worker should be running whenever your app is running, typically as a background process,
so that it can pick up any tasks that get queued. Learn more from the `Celery Workers Guide`_.
The project comes with a simple task for manual testing purposes, inside `/users/tasks.py`. To queue that task locally, start the Django shell, import the task, and call `delay()` on it::
uv run python manage.py shell
>> from .users.tasks import get_users_count
>> get_users_count.delay()
You can also use Django admin to queue up tasks, thanks to the `django-celerybeat`_ package.
.. _Getting started with Redis: https://redis.io/docs/latest/get-started/
.. _Celery Workers Guide: https://docs.celeryq.dev/en/stable/userguide/workers.html
.. _django-celerybeat: https://django-celery-beat.readthedocs.io/en/latest/
.. _bare-metal-webpack-gulp:
Using Webpack or Gulp
---------------------
If you've opted for Gulp or Webpack as front-end pipeline, the project comes configured with `Sass`_ compilation and `live reloading`_. As you change your Sass/JS source files, the task runner will automatically rebuild the corresponding CSS and JS assets and reload them in your browser without refreshing the page.
#. Make sure that `Node.js`_ v18 is installed on your machine.
#. In the project root, install the JS dependencies with::
npm install
#. Now - with your virtualenv activated - start the application by running::
npm run dev
This will start 2 processes in parallel: the static assets build loop on one side, and the Django server on the other.
#. Access your application at the address of the ``node`` service in order to see your correct styles. This is http://localhost:3000 by default.
.. note:: Do NOT access the application using the Django port (8000 by default), as it will result in broken styles and 404s when accessing static assets.
.. _Node.js: http://nodejs.org/download/
.. _Sass: https://sass-lang.com/
.. _live reloading: https://browsersync.io
Summary
-------
Congratulations, you have made it! Keep on reading to unleash full potential of Cookiecutter Django.