Compare commits

..

No commits in common. "master" and "2024.02.13" have entirely different histories.

176 changed files with 1852 additions and 5830 deletions

View File

@ -12,7 +12,7 @@ trim_trailing_whitespace = true
indent_style = space
indent_size = 4
[*.{html,css,scss,json,yml,xml,toml}]
[*.{html,css,scss,json,yml,xml}]
indent_style = space
indent_size = 2

2
.github/FUNDING.yml vendored
View File

@ -1,5 +1,5 @@
# These are supported funding model platforms
github: [pydanny, browniebroke, luzfcb]
github: [pydanny, browniebroke]
patreon: feldroy
open_collective: cookiecutter-django

View File

@ -1115,7 +1115,7 @@
"twitter_username": "Qoyyuum"
},
{
"name": "Matthew Foster Walsh",
"name": "mfosterw",
"github_login": "mfosterw",
"twitter_username": ""
},
@ -1518,200 +1518,5 @@
"name": "henningbra",
"github_login": "henningbra",
"twitter_username": ""
},
{
"name": "Paul Wulff",
"github_login": "mtmpaulwulff",
"twitter_username": ""
},
{
"name": "Mounir",
"github_login": "mounirmesselmeni",
"twitter_username": ""
},
{
"name": "JAEGYUN JUNG",
"github_login": "TGoddessana",
"twitter_username": ""
},
{
"name": "Simeon Emanuilov",
"github_login": "s-emanuilov",
"twitter_username": "s_emanuilov"
},
{
"name": "Patrick Zhang",
"github_login": "PatDuJour",
"twitter_username": ""
},
{
"name": "GvS",
"github_login": "GvS666",
"twitter_username": ""
},
{
"name": "David Păcioianu",
"github_login": "DavidPacioianu",
"twitter_username": ""
},
{
"name": "farwill",
"github_login": "farwill",
"twitter_username": ""
},
{
"name": "quroom",
"github_login": "quroom",
"twitter_username": ""
},
{
"name": "Marios Frixou",
"github_login": "frixou89",
"twitter_username": ""
},
{
"name": "Geo Maciolek",
"github_login": "GeoMaciolek",
"twitter_username": ""
},
{
"name": "Nadav Peretz",
"github_login": "nadavperetz",
"twitter_username": ""
},
{
"name": "Param Kapur",
"github_login": "paramkpr",
"twitter_username": "ParamKapur"
},
{
"name": "Jason Mok",
"github_login": "jasonmokk",
"twitter_username": ""
},
{
"name": "Manas Mallick",
"github_login": "ManDun",
"twitter_username": ""
},
{
"name": "Alexandr Artemyev",
"github_login": "Mogost",
"twitter_username": "MOGOST"
},
{
"name": "Ali Shamakhi",
"github_login": "ali-shamakhi",
"twitter_username": ""
},
{
"name": "Filipe Nascimento",
"github_login": "FilipeNas",
"twitter_username": ""
},
{
"name": "Kevin Mills",
"github_login": "millsks",
"twitter_username": ""
},
{
"name": "milvagox",
"github_login": "milvagox",
"twitter_username": "milvagox"
},
{
"name": "Johnny Metz",
"github_login": "johnnymetz",
"twitter_username": ""
},
{
"name": "Will",
"github_login": "novucs",
"twitter_username": ""
},
{
"name": "rxm7706",
"github_login": "rxm7706",
"twitter_username": ""
},
{
"name": "Marlon Castillo",
"github_login": "mcastle",
"twitter_username": ""
},
{
"name": "Alex Kanavos",
"github_login": "alexkanavos",
"twitter_username": ""
},
{
"name": "LJFP",
"github_login": "ljfp",
"twitter_username": ""
},
{
"name": "Francisco Navarro Morales ",
"github_login": "spothound",
"twitter_username": ""
},
{
"name": "Mariot Tsitoara",
"github_login": "mariot",
"twitter_username": ""
},
{
"name": "Christian Jensen",
"github_login": "jensenbox",
"twitter_username": "cjensen"
},
{
"name": "Denis Darii",
"github_login": "DNX",
"twitter_username": ""
},
{
"name": "qwerrrqw",
"github_login": "qwerrrqw",
"twitter_username": ""
},
{
"name": "Pulse-Mind",
"github_login": "pulse-mind",
"twitter_username": ""
},
{
"name": "Hana Belay",
"github_login": "earthcomfy",
"twitter_username": ""
},
{
"name": "Ed Morley",
"github_login": "edmorley",
"twitter_username": ""
},
{
"name": "Alan Cyment",
"github_login": "acyment",
"twitter_username": ""
},
{
"name": "Kawsar Alam Foysal",
"github_login": "iamfoysal",
"twitter_username": ""
},
{
"name": "Igor Jerosimić",
"github_login": "igor-wl",
"twitter_username": ""
},
{
"name": "Pepa",
"github_login": "07pepa",
"twitter_username": ""
},
{
"name": "Aidos Kanapyanov",
"github_login": "aidoskanapyanov",
"twitter_username": ""
}
]

View File

@ -1,17 +1,8 @@
# Config for Dependabot updates. See Documentation here:
# https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
# https://docs.github.com/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/configuration-options-for-dependency-updates
version: 2
enable-beta-ecosystems: true
updates:
# Update Python deps for the template (not the generated project)
- package-ecosystem: "uv"
directory: "/"
schedule:
interval: "daily"
labels:
- "project infrastructure"
# Update GitHub actions in workflows
- package-ecosystem: "github-actions"
directory: "/"
@ -29,11 +20,11 @@ updates:
- "update"
# Enable version updates for Docker
# We need to specify each Dockerfile in a separate entry because Dependabot doesn't
# support wildcards or recursively checking subdirectories. Check this issue for updates:
# https://github.com/dependabot/dependabot-core/issues/2178
- package-ecosystem: "docker"
directories:
- "{{cookiecutter.project_slug}}/compose/local/django/"
- "{{cookiecutter.project_slug}}/compose/local/docs/"
- "{{cookiecutter.project_slug}}/compose/production/django/"
directory: "{{cookiecutter.project_slug}}/compose/local/django/"
schedule:
interval: "daily"
ignore:
@ -43,18 +34,54 @@ updates:
- "version-update:semver-minor"
labels:
- "update"
groups:
docker-python:
patterns:
- "*"
- package-ecosystem: "docker"
directories:
- "{{cookiecutter.project_slug}}/compose/local/node/"
- "{{cookiecutter.project_slug}}/compose/production/aws/"
- "{{cookiecutter.project_slug}}/compose/production/postgres/"
- "{{cookiecutter.project_slug}}/compose/production/nginx/"
- "{{cookiecutter.project_slug}}/compose/production/traefik/"
directory: "{{cookiecutter.project_slug}}/compose/local/docs/"
schedule:
interval: "daily"
ignore:
- dependency-name: "*"
update-types:
- "version-update:semver-major"
- "version-update:semver-minor"
labels:
- "update"
- package-ecosystem: "docker"
directory: "{{cookiecutter.project_slug}}/compose/local/node/"
schedule:
interval: "daily"
labels:
- "update"
- package-ecosystem: "docker"
directory: "{{cookiecutter.project_slug}}/compose/production/aws/"
schedule:
interval: "daily"
labels:
- "update"
- package-ecosystem: "docker"
directory: "{{cookiecutter.project_slug}}/compose/production/django/"
schedule:
interval: "daily"
ignore:
- dependency-name: "*"
update-types:
- "version-update:semver-major"
- "version-update:semver-minor"
labels:
- "update"
- package-ecosystem: "docker"
directory: "{{cookiecutter.project_slug}}/compose/production/postgres/"
schedule:
interval: "daily"
labels:
- "update"
- package-ecosystem: "docker"
directory: "{{cookiecutter.project_slug}}/compose/production/traefik/"
schedule:
interval: "daily"
labels:

View File

@ -1,52 +0,0 @@
name: align versions
on:
pull_request:
paths:
- "{{cookiecutter.project_slug}}/requirements/local.txt"
- "{{cookiecutter.project_slug}}/compose/local/node/Dockerfile"
# Manual trigger
workflow_dispatch:
permissions:
contents: write
pull-requests: write
jobs:
run:
if: ${{ github.actor == 'pyup-bot' }}
runs-on: ubuntu-latest
env:
GH_PAT: ${{ secrets.GH_PAT }}
strategy:
fail-fast: false
matrix:
job:
- script: scripts/ruff_version.py
name: Ruff
- script: scripts/node_version.py
name: Node
name: "${{ matrix.job.name }} versions"
steps:
- name: Checkout with token
uses: actions/checkout@v4
if: ${{ env.GH_PAT != '' }}
with:
token: ${{ env.GH_PAT }}
ref: ${{ github.head_ref }}
- name: Checkout without token
uses: actions/checkout@v4
if: ${{ env.GH_PAT == '' }}
with:
ref: ${{ github.head_ref }}
- uses: astral-sh/setup-uv@v5
- run: uv run ${{ matrix.job.script }}
- uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: Align versions

View File

@ -23,12 +23,14 @@ jobs:
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v5
- uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip
- name: Install dependencies
run: uv sync
run: pip install -r requirements.txt
- name: Run tests
run: uv run pytest -n auto tests
run: pytest -n auto tests
docker:
strategy:
@ -52,10 +54,12 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v5
- uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip
- name: Install dependencies
run: uv sync
run: pip install -r requirements.txt
- name: Docker ${{ matrix.script.name }}
run: sh tests/test_docker.sh ${{ matrix.script.args }}
@ -81,14 +85,14 @@ jobs:
ports:
- 6379:6379
postgres:
image: postgres:13
image: postgres:12
ports:
- 5432:5432
env:
POSTGRES_PASSWORD: postgres
env:
REDIS_URL: "redis://localhost:6379/0"
CELERY_BROKER_URL: "redis://localhost:6379/0"
# postgres://user:password@host:port/database
DATABASE_URL: "postgres://postgres:postgres@localhost:5432/postgres"
@ -96,13 +100,16 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install uv
uses: astral-sh/setup-uv@v5
python-version: "3.11"
cache: pip
cache-dependency-path: |
requirements.txt
{{cookiecutter.project_slug}}/requirements/base.txt
{{cookiecutter.project_slug}}/requirements/local.txt
- name: Install dependencies
run: uv sync
run: pip install -r requirements.txt
- uses: actions/setup-node@v4
with:
node-version: "22.14"
node-version: "20"
- name: Bare Metal ${{ matrix.script.name }}
run: sh tests/test_bare.sh ${{ matrix.script.args }}

View File

@ -1,33 +0,0 @@
name: uv
on:
pull_request:
paths:
- "pyproject.toml"
permissions:
contents: write
pull-requests: write
jobs:
lock:
if: ${{ github.actor == 'dependabot[bot]' }}
runs-on: ubuntu-latest
env:
GH_PAT: ${{ secrets.GH_PAT }}
steps:
- name: Checkout with token
uses: actions/checkout@v4
if: ${{ env.GH_PAT != '' }}
with:
token: ${{ env.GH_PAT }}
- name: Checkout without token
uses: actions/checkout@v4
if: ${{ env.GH_PAT == '' }}
- uses: astral-sh/setup-uv@v5
- run: uv lock
- uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: Regenerate uv.lock

View File

@ -17,9 +17,14 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v5
- uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Create Django Major Issue
run: uv run --frozen scripts/create_django_issue.py
run: python scripts/create_django_issue.py
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@ -23,7 +23,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: tiangolo/issue-manager@0.5.1
- uses: tiangolo/issue-manager@0.5.0
with:
token: ${{ secrets.GITHUB_TOKEN }}
config: >

View File

@ -24,7 +24,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
python-version: "3.11"
- name: Install pre-commit
run: pip install pre-commit
@ -37,7 +37,7 @@ jobs:
run: pre-commit autoupdate
- name: Create Pull Request
uses: peter-evans/create-pull-request@v7
uses: peter-evans/create-pull-request@v6
with:
token: ${{ secrets.GITHUB_TOKEN }}
branch: update/pre-commit-autoupdate

View File

@ -8,20 +8,27 @@ on:
workflow_dispatch:
jobs:
update:
release:
# Disables this workflow from running in a repository that is not part of the indicated organization/user
if: github.repository_owner == 'cookiecutter'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v5
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Set git details
run: |
git config --global user.name "github-actions"
git config --global user.email "action@github.com"
- name: Update changelog
run: uv run --frozen scripts/update_changelog.py
- name: Update list
run: python scripts/update_changelog.py
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@ -18,15 +18,22 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v5
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Update list
run: uv run --frozen scripts/update_contributors.py
run: python scripts/update_contributors.py
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Commit changes
uses: stefanzweifel/git-auto-commit-action@v5.0.1
uses: stefanzweifel/git-auto-commit-action@v5.0.0
with:
commit_message: Update Contributors
file_pattern: CONTRIBUTORS.md .github/contributors.json

View File

@ -1,13 +1,12 @@
exclude: "{{cookiecutter.project_slug}}|.github/contributors.json|CHANGELOG.md|CONTRIBUTORS.md"
default_stages: [pre-commit]
minimum_pre_commit_version: "3.2.0"
default_stages: [commit]
default_language_version:
python: python3.12
python: python3.11
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
rev: v4.5.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
@ -27,32 +26,27 @@ repos:
args: ["--tab-width", "2"]
- repo: https://github.com/asottile/pyupgrade
rev: v3.19.1
rev: v3.15.0
hooks:
- id: pyupgrade
args: [--py312-plus]
args: [--py311-plus]
exclude: hooks/
- repo: https://github.com/psf/black
rev: 25.1.0
rev: 24.2.0
hooks:
- id: black
- repo: https://github.com/PyCQA/isort
rev: 6.0.1
rev: 5.13.2
hooks:
- id: isort
- repo: https://github.com/PyCQA/flake8
rev: 7.2.0
rev: 7.0.0
hooks:
- id: flake8
- repo: https://github.com/tox-dev/pyproject-fmt
rev: "v2.5.1"
hooks:
- id: pyproject-fmt
ci:
autoupdate_schedule: weekly
skip: []

View File

@ -14,6 +14,8 @@ pin: True
label_prs: update
requirements:
- "requirements.txt"
- "docs/requirements.txt"
- "{{cookiecutter.project_slug}}/requirements/base.txt"
- "{{cookiecutter.project_slug}}/requirements/local.txt"
- "{{cookiecutter.project_slug}}/requirements/production.txt"

View File

@ -8,14 +8,13 @@ version: 2
build:
os: ubuntu-22.04
tools:
python: "3.12"
commands:
- asdf plugin add uv
- asdf install uv latest
- asdf global uv latest
- uv sync --only-group docs --frozen
- uv run -m sphinx -T -b html -d docs/_build/doctrees -D language=en docs $READTHEDOCS_OUTPUT/html
python: "3.11"
# Build documentation in the docs/ directory with Sphinx
sphinx:
configuration: docs/conf.py
# Declare the Python requirements required to build your docs
python:
install:
- requirements: docs/requirements.txt

File diff suppressed because it is too large Load Diff

View File

@ -18,26 +18,39 @@ This last step is very important, don't start developing from master, it'll caus
## Testing
You'll need to run the tests using Python 3.12. We recommend using [tox](https://tox.readthedocs.io/en/latest/) to run the tests. It will automatically create a fresh virtual environment and install our test dependencies, such as [pytest-cookies](https://pypi.python.org/pypi/pytest-cookies/) and [flake8](https://pypi.python.org/pypi/flake8/).
You'll need to run the tests using Python 3.11. We recommend using [tox](https://tox.readthedocs.io/en/latest/) to run the tests. It will automatically create a fresh virtual environment and install our test dependencies, such as [pytest-cookies](https://pypi.python.org/pypi/pytest-cookies/) and [flake8](https://pypi.python.org/pypi/flake8/).
We'll also run the tests on GitHub actions when you send your pull request, but it's a good idea to run them locally before you send it.
### Installation
We use uv to manage our environment and manage our Python installation. You can install it following the instructions at https://docs.astral.sh/uv/getting-started/installation/
First, make sure that your version of Python is 3.11:
```bash
$ python --version
Python 3.11.3
```
Any version that starts with 3.11 will do. If you need to install it, you can get it from [python.org](https://www.python.org/downloads/).
Then install `tox`, if not already installed:
```bash
$ python -m pip install tox
```
### Run the template's test suite
To run the tests of the template using the current Python version:
```bash
$ uv run tox run -e py
$ tox -e py
```
This uses `pytest `under the hood, and you can pass options to it after a `--`. So to run a particular test:
```bash
$ uv run tox run -e py -- -k test_default_configuration
$ tox -e py -- -k test_default_configuration
```
For further information, please consult the [pytest usage docs](https://pytest.org/en/latest/how-to/usage.html#specifying-which-tests-to-run).
@ -53,13 +66,13 @@ $ source venv/bin/activate
These tests are slower and can be run with or without Docker:
- Without Docker: `tests/test_bare.sh` (for bare metal)
- With Docker: `tests/test_docker.sh`
- Without Docker: `scripts/test_bare.sh` (for bare metal)
- With Docker: `scripts/test_docker.sh`
All arguments to these scripts will be passed to the `cookiecutter` CLI, letting you set options, for example:
```bash
$ tests/test_bare.sh use_celery=y
$ scripts/test_bare.sh use_celery=y
```
## Submitting a pull request

View File

@ -201,20 +201,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>Aidos Kanapyanov</td>
<td>
<a href="https://github.com/aidoskanapyanov">aidoskanapyanov</a>
</td>
<td></td>
</tr>
<tr>
<td>Alan Cyment</td>
<td>
<a href="https://github.com/acyment">acyment</a>
</td>
<td></td>
</tr>
<tr>
<td>Alberto Sanchez</td>
<td>
@ -222,13 +208,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>Alex Kanavos</td>
<td>
<a href="https://github.com/alexkanavos">alexkanavos</a>
</td>
<td></td>
</tr>
<tr>
<td>Alex Tsai</td>
<td>
@ -236,20 +215,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>Alexandr Artemyev</td>
<td>
<a href="https://github.com/Mogost">Mogost</a>
</td>
<td>MOGOST</td>
</tr>
<tr>
<td>Ali Shamakhi</td>
<td>
<a href="https://github.com/ali-shamakhi">ali-shamakhi</a>
</td>
<td></td>
</tr>
<tr>
<td>Alvaro [Andor]</td>
<td>
@ -558,13 +523,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>Christian Jensen</td>
<td>
<a href="https://github.com/jensenbox">jensenbox</a>
</td>
<td>cjensen</td>
</tr>
<tr>
<td>Christopher Clarke</td>
<td>
@ -698,13 +656,6 @@ Listed in alphabetical order.
</td>
<td>DavidDiazPinto</td>
</tr>
<tr>
<td>David Păcioianu</td>
<td>
<a href="https://github.com/DavidPacioianu">DavidPacioianu</a>
</td>
<td></td>
</tr>
<tr>
<td>Davit Tovmasyan</td>
<td>
@ -747,13 +698,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>Denis Darii</td>
<td>
<a href="https://github.com/DNX">DNX</a>
</td>
<td></td>
</tr>
<tr>
<td>Denis Orehovsky</td>
<td>
@ -817,13 +761,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>Ed Morley</td>
<td>
<a href="https://github.com/edmorley">edmorley</a>
</td>
<td></td>
</tr>
<tr>
<td>Emanuel Calso</td>
<td>
@ -873,13 +810,6 @@ Listed in alphabetical order.
</td>
<td>fabaff</td>
</tr>
<tr>
<td>farwill</td>
<td>
<a href="https://github.com/farwill">farwill</a>
</td>
<td></td>
</tr>
<tr>
<td>Fateme Fouladkar</td>
<td>
@ -894,13 +824,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>Filipe Nascimento</td>
<td>
<a href="https://github.com/FilipeNas">FilipeNas</a>
</td>
<td></td>
</tr>
<tr>
<td>Florian Idelberger</td>
<td>
@ -915,13 +838,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>Francisco Navarro Morales </td>
<td>
<a href="https://github.com/spothound">spothound</a>
</td>
<td></td>
</tr>
<tr>
<td>Freddy</td>
<td>
@ -957,13 +873,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>Geo Maciolek</td>
<td>
<a href="https://github.com/GeoMaciolek">GeoMaciolek</a>
</td>
<td></td>
</tr>
<tr>
<td>ghazi-git</td>
<td>
@ -1006,13 +915,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>GvS</td>
<td>
<a href="https://github.com/GvS666">GvS666</a>
</td>
<td></td>
</tr>
<tr>
<td>Hamish Durkin</td>
<td>
@ -1020,13 +922,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>Hana Belay</td>
<td>
<a href="https://github.com/earthcomfy">earthcomfy</a>
</td>
<td></td>
</tr>
<tr>
<td>Hana Quadara</td>
<td>
@ -1111,13 +1006,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>Igor Jerosimić</td>
<td>
<a href="https://github.com/igor-wl">igor-wl</a>
</td>
<td></td>
</tr>
<tr>
<td>Imran Rahman</td>
<td>
@ -1160,13 +1048,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>JAEGYUN JUNG</td>
<td>
<a href="https://github.com/TGoddessana">TGoddessana</a>
</td>
<td></td>
</tr>
<tr>
<td>Jakub Boukal</td>
<td>
@ -1202,13 +1083,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>Jason Mok</td>
<td>
<a href="https://github.com/jasonmokk">jasonmokk</a>
</td>
<td></td>
</tr>
<tr>
<td>Jens Kaeske</td>
<td>
@ -1258,13 +1132,6 @@ Listed in alphabetical order.
</td>
<td>cass_john</td>
</tr>
<tr>
<td>Johnny Metz</td>
<td>
<a href="https://github.com/johnnymetz">johnnymetz</a>
</td>
<td></td>
</tr>
<tr>
<td>Jonathan Thompson</td>
<td>
@ -1335,13 +1202,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>Kawsar Alam Foysal</td>
<td>
<a href="https://github.com/iamfoysal">iamfoysal</a>
</td>
<td></td>
</tr>
<tr>
<td>Keith Bailey</td>
<td>
@ -1370,13 +1230,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>Kevin Mills</td>
<td>
<a href="https://github.com/millsks">millsks</a>
</td>
<td></td>
</tr>
<tr>
<td>Kevin Ndung&#39;u</td>
<td>
@ -1482,13 +1335,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>LJFP</td>
<td>
<a href="https://github.com/ljfp">ljfp</a>
</td>
<td></td>
</tr>
<tr>
<td>Luis Nell</td>
<td>
@ -1517,13 +1363,6 @@ Listed in alphabetical order.
</td>
<td>flyudvik</td>
</tr>
<tr>
<td>Manas Mallick</td>
<td>
<a href="https://github.com/ManDun">ManDun</a>
</td>
<td></td>
</tr>
<tr>
<td>Manjit Pardeshi</td>
<td>
@ -1538,27 +1377,6 @@ Listed in alphabetical order.
</td>
<td>marciomazza</td>
</tr>
<tr>
<td>Marios Frixou</td>
<td>
<a href="https://github.com/frixou89">frixou89</a>
</td>
<td></td>
</tr>
<tr>
<td>Mariot Tsitoara</td>
<td>
<a href="https://github.com/mariot">mariot</a>
</td>
<td></td>
</tr>
<tr>
<td>Marlon Castillo</td>
<td>
<a href="https://github.com/mcastle">mcastle</a>
</td>
<td></td>
</tr>
<tr>
<td>Martin Blech</td>
<td>
@ -1636,13 +1454,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>Matthew Foster Walsh</td>
<td>
<a href="https://github.com/mfosterw">mfosterw</a>
</td>
<td></td>
</tr>
<tr>
<td>Matthew Sisley</td>
<td>
@ -1678,6 +1489,13 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>mfosterw</td>
<td>
<a href="https://github.com/mfosterw">mfosterw</a>
</td>
<td></td>
</tr>
<tr>
<td>Michael Gecht</td>
<td>
@ -1706,13 +1524,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>milvagox</td>
<td>
<a href="https://github.com/milvagox">milvagox</a>
</td>
<td>milvagox</td>
</tr>
<tr>
<td>Min ho Kim</td>
<td>
@ -1741,13 +1552,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>Mounir</td>
<td>
<a href="https://github.com/mounirmesselmeni">mounirmesselmeni</a>
</td>
<td></td>
</tr>
<tr>
<td>mozillazg</td>
<td>
@ -1769,13 +1573,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>Nadav Peretz</td>
<td>
<a href="https://github.com/nadavperetz">nadavperetz</a>
</td>
<td></td>
</tr>
<tr>
<td>Naveen</td>
<td>
@ -1839,13 +1636,6 @@ Listed in alphabetical order.
</td>
<td>pamelafox</td>
</tr>
<tr>
<td>Param Kapur</td>
<td>
<a href="https://github.com/paramkpr">paramkpr</a>
</td>
<td>ParamKapur</td>
</tr>
<tr>
<td>Parbhat Puri</td>
<td>
@ -1860,20 +1650,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>Patrick Zhang</td>
<td>
<a href="https://github.com/PatDuJour">PatDuJour</a>
</td>
<td></td>
</tr>
<tr>
<td>Paul Wulff</td>
<td>
<a href="https://github.com/mtmpaulwulff">mtmpaulwulff</a>
</td>
<td></td>
</tr>
<tr>
<td>Pawan Chaurasia</td>
<td>
@ -1888,13 +1664,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>Pepa</td>
<td>
<a href="https://github.com/07pepa">07pepa</a>
</td>
<td></td>
</tr>
<tr>
<td>Peter Bittner</td>
<td>
@ -1937,27 +1706,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>Pulse-Mind</td>
<td>
<a href="https://github.com/pulse-mind">pulse-mind</a>
</td>
<td></td>
</tr>
<tr>
<td>quroom</td>
<td>
<a href="https://github.com/quroom">quroom</a>
</td>
<td></td>
</tr>
<tr>
<td>qwerrrqw</td>
<td>
<a href="https://github.com/qwerrrqw">qwerrrqw</a>
</td>
<td></td>
</tr>
<tr>
<td>Raony Guimarães Corrêa</td>
<td>
@ -2035,13 +1783,6 @@ Listed in alphabetical order.
</td>
<td></td>
</tr>
<tr>
<td>rxm7706</td>
<td>
<a href="https://github.com/rxm7706">rxm7706</a>
</td>
<td></td>
</tr>
<tr>
<td>Ryan Fitch</td>
<td>
@ -2084,13 +1825,6 @@ Listed in alphabetical order.
</td>
<td>shywn_mrk</td>
</tr>
<tr>
<td>Simeon Emanuilov</td>
<td>
<a href="https://github.com/s-emanuilov">s-emanuilov</a>
</td>
<td>s_emanuilov</td>
</tr>
<tr>
<td>Simon Rey</td>
<td>
@ -2343,13 +2077,6 @@ Listed in alphabetical order.
</td>
<td>westurner</td>
</tr>
<tr>
<td>Will</td>
<td>
<a href="https://github.com/novucs">novucs</a>
</td>
<td></td>
</tr>
<tr>
<td>Will Farley</td>
<td>

View File

@ -6,21 +6,21 @@
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/ambv/black)
[![Updates](https://pyup.io/repos/github/cookiecutter/cookiecutter-django/shield.svg)](https://pyup.io/repos/github/cookiecutter/cookiecutter-django/)
[![Join our Discord](https://img.shields.io/badge/Discord-cookiecutter-5865F2?style=flat&logo=discord&logoColor=white)](https://discord.gg/rAWFUP47d2)
[![Join our Discord](https://img.shields.io/badge/Discord-cookiecutter-5865F2?style=flat&logo=discord&logoColor=white)](https://discord.gg/uFXweDQc5a)
[![Code Helpers Badge](https://www.codetriage.com/cookiecutter/cookiecutter-django/badges/users.svg)](https://www.codetriage.com/cookiecutter/cookiecutter-django)
Powered by [Cookiecutter](https://github.com/cookiecutter/cookiecutter), Cookiecutter Django is a framework for jumpstarting
production-ready Django projects quickly.
- Documentation: <https://cookiecutter-django.readthedocs.io/en/latest/>
- See [Troubleshooting](https://cookiecutter-django.readthedocs.io/en/latest/5-help/troubleshooting.html) for common errors and obstacles
- See [Troubleshooting](https://cookiecutter-django.readthedocs.io/en/latest/troubleshooting.html) for common errors and obstacles
- If you have problems with Cookiecutter Django, please open [issues](https://github.com/cookiecutter/cookiecutter-django/issues/new) don't send
emails to the maintainers.
## Features
- For Django 5.1
- Works with Python 3.12
- For Django 4.2
- Works with Python 3.11
- Renders Django projects with 100% starting test coverage
- Twitter [Bootstrap](https://github.com/twbs/bootstrap) v5
- [12-Factor](https://12factor.net) based settings via [django-environ](https://github.com/joke2k/django-environ)
@ -51,7 +51,7 @@ _These features can be enabled during initial project setup._
## Constraints
- Only maintained 3rd party libraries are used.
- Uses PostgreSQL everywhere: 13 - 16 ([MySQL fork](https://github.com/mabdullahadeel/cookiecutter-django-mysql) also available).
- Uses PostgreSQL everywhere: 10 - 15 ([MySQL fork](https://github.com/mabdullahadeel/cookiecutter-django-mysql) also available).
- Environment variables for configuration (This won't work with Apache/mod_wsgi).
## Support this Project!
@ -65,15 +65,19 @@ This project is an open source project run by volunteers. You can sponsor us via
Projects that provide financial support to the maintainers:
### Two Scoops of Django
---
[![Cover of the book "Two Scoops of Django 3.x"](https://f004.backblazeb2.com/file/feldroycom/images/book-TSD3-800.jpg)](https://www.feldroy.com/two-scoops-press#two-scoops-of-django)
<p align="center">
<a href="https://www.feldroy.com/products//two-scoops-of-django-3-x"><img src="https://cdn.shopify.com/s/files/1/0304/6901/products/Two-Scoops-of-Django-3-Alpha-Cover_540x_26507b15-e489-470b-8a97-02773dd498d1_1080x.jpg"></a>
</p>
Two Scoops of Django 3.x is the best ice cream-themed Django reference in the universe!
### PyUp
[![PyUp Logo](https://pyup.io/static/images/logo.png)](https://pyup.io)
<p align="center">
<a href="https://pyup.io/"><img src="https://pyup.io/static/images/logo.png"></a>
</p>
PyUp brings you automated security and dependency updates used by Google and other organizations. Free for open source projects!
@ -94,7 +98,7 @@ You'll be prompted for some values. Provide them, then a Django project will be
**Warning**: After this point, change 'Daniel Greenfeld', 'pydanny', etc to your own information.
Answer the prompts with your own desired [options](http://cookiecutter-django.readthedocs.io/en/latest/1-getting-started/project-generation-options.html). For example:
Answer the prompts with your own desired [options](http://cookiecutter-django.readthedocs.io/en/latest/project-generation-options.html). For example:
Cloning into 'cookiecutter-django'...
remote: Counting objects: 550, done.
@ -129,11 +133,13 @@ Answer the prompts with your own desired [options](http://cookiecutter-django.re
Choose from 1, 2, 3 [1]: 1
use_docker [n]: n
Select postgresql_version:
1 - 16
2 - 15
3 - 14
4 - 13
Choose from 1, 2, 3, 4 [1]: 1
1 - 15
2 - 14
3 - 13
4 - 12
5 - 11
6 - 10
Choose from 1, 2, 3, 4, 5 [1]: 1
Select cloud_provider:
1 - AWS
2 - GCP
@ -146,7 +152,7 @@ Answer the prompts with your own desired [options](http://cookiecutter-django.re
4 - Mandrill
5 - Postmark
6 - Sendgrid
7 - Brevo (formerly SendinBlue)
7 - SendinBlue
8 - SparkPost
9 - Other SMTP
Choose from 1, 2, 3, 4, 5, 6, 7, 8, 9 [1]: 1
@ -189,8 +195,8 @@ Now take a look at your repo. Don't forget to carefully look at the generated RE
For local development, see the following:
- [Developing locally](https://cookiecutter-django.readthedocs.io/en/latest/2-local-development/developing-locally.html)
- [Developing locally using docker](https://cookiecutter-django.readthedocs.io/en/latest/2-local-development/developing-locally-docker.html)
- [Developing locally](http://cookiecutter-django.readthedocs.io/en/latest/developing-locally.html)
- [Developing locally using docker](http://cookiecutter-django.readthedocs.io/en/latest/developing-locally-docker.html)
## Community
@ -243,7 +249,6 @@ experience better.
## Articles
- [Why cookiecutter-django is Essential for Your Next Django Project](https://medium.com/@millsks/why-cookiecutter-django-is-essential-for-your-next-django-project-7d3c00cdce51) - Aug. 4, 2024
- [How to Make Your Own Django Cookiecutter Template!](https://medium.com/@FatemeFouladkar/how-to-make-your-own-django-cookiecutter-template-a753d4cbb8c2) - Aug. 10, 2023
- [Cookiecutter Django With Amazon RDS](https://haseeburrehman.com/posts/cookiecutter-django-with-amazon-rds/) - Apr, 2, 2021
- [Complete Walkthrough: Blue/Green Deployment to AWS ECS using GitHub actions](https://github.com/Andrew-Chen-Wang/cookiecutter-django-ecs-github) - June 10, 2020

View File

@ -18,7 +18,7 @@
"windows": "n",
"editor": ["None", "PyCharm", "VS Code"],
"use_docker": "n",
"postgresql_version": ["16", "15", "14", "13"],
"postgresql_version": ["15", "14", "13", "12", "11", "10"],
"cloud_provider": ["AWS", "GCP", "Azure", "None"],
"mail_service": [
"Mailgun",
@ -27,7 +27,7 @@
"Mandrill",
"Postmark",
"Sendgrid",
"Brevo",
"SendinBlue",
"SparkPost",
"Other SMTP"
],

View File

@ -1,3 +0,0 @@
```{include} ../../CONTRIBUTING.md
```

View File

@ -1,104 +0,0 @@
# Maintainer guide
This document is intended for maintainers of the template.
## Automated updates
We use 2 separate services to keep our dependencies up-to-date:
- Dependabot, which manages updates of Python deps of the template, GitHub actions, npm packages and Docker images.
- PyUp, which manages the Python deps for the generated project.
We don't use Dependabot for the generated project deps because our requirements files are templated, and Dependabot fails to parse them. PyUp is -AFAIK- the only service out there that supports having Jinja tags in the requirements file.
Updates for the template should be labelled as `project infrastructure` while the ones about the generated project should be labelled as `update`. This is use to work in conjunction with our changelog script (see later).
## Automation scripts
We have a few workflows which have been automated over time. They usually run using GitHub actions and might need a few small manual actions to work nicely. Some have a few limitations which we should document here.
### CI
`ci.yml`
The CI workflow tries to cover 2 main aspects of the template:
- Check all combinations to make sure that valid files are generated with no major linting issues. Issues which are fixed by an auto-formatter after generation aren't considered major, and only aim for best effort. This is under the `test` job.
- Run more in-depth tests on a few combinations, by installing dependencies, running type checker and the test suite of the generated project. We try to cover docker (`docker` job) and non-docker (`bare` job) setups.
We also run the deployment checks, but we don't do much more beyond that for testing the production setup.
### Django issue checker
`django-issue-checker.yml`
This workflow runs daily, on schedule, and checks if there is a new major version of Django (not in the pure SemVer sense) released that we are not running, and list our dependencies compatibility.
For example, at time of writing, we use Django 4.2, but the latest version of Django is 5.0, so the workflow created a ["Django 5.0" issue](https://github.com/cookiecutter/cookiecutter-django/issues/4724) in GitHub, with a compatibility table and keeps it up to date every day.
#### Limitations
Here are a few current and past limitations of the script
- When a new dependency is added to the template, the script fails to update an existing issue
- Not sure what happens when a deps is removed
- ~~Unable to parse classifiers without minor version~~
- ~~Creates an issue even if we are on the latest version~~
### Issue manager
`issue-manager.yml`
A workflow that uses [Sebastian Ramirez' issue-manager](https://github.com/tiangolo/issue-manager) to help us automate issue management. The tag line from the repo explains it well:
> Automatically close issues or Pull Requests that have a label, after a custom delay, if no one replies back.
It runs on a schedule as well as when some actions are taken on issues and pull requests.
We wait 10 days before closing issues, and we have a few customised reasons, which are configured in the workflow itself. The config should be fairly self-explanatory.
### Pre-commit auto-update
`pre-commit-autoupdate.yml`
Run daily, to do `pre-commit autoupdate` on the template as well as the generated project, and opens a pull request with the changes.
#### Limitations
- The PR is open as GitHub action which means that CI does NOT run. The documentation for create-pull-request action [explains why](https://github.com/peter-evans/create-pull-request/blob/main/docs/concepts-guidelines.md#triggering-further-workflow-runs).
- Some hooks are also installed as local dependencies (via `requirements/local.txt`), but these are updated separately via PyUP.
### Update changelog
`update-changelog.yml`
Run daily at 2AM to update our changelog and create a GitHub release. This runs a custom script which:
- List all pull requests merged the day before
- The release name is calendar based, so `YYYY.MM.DD`
- For each PR:
- Get the PR title to summarize the change
- Look at the PR labels to classify it in a section of the release notes:
- anything labelled `project infrastructure` is excluded
- label `update` goes in section "Updated"
- label `bug` goes in section "Fixed"
- label `docs` goes in section "Documentation"
- Default to section "Changed"
With that in mind, when merging changes, it's a good idea to set the labels and rename the PR title to give a good summary of the change, in the context of the changelog.
#### Limitations
- Dependabot updates for npm & Docker have a verbose title, try to rename them to be more readable: `Bump webpack-dev-server from 4.15.1 to 5.0.2 in /{{cookiecutter.project_slug}}` -> `Bump webpack-dev-server to 5.0.2`
- ~~Dependencies updates for the template repo (tox, cookiecutter, etc...) don't need to appear in changelog, and need to be labelled as `project infrastructure` manually. By default, they come from PyUp labelled as `update`.~~
### Update contributors
`update-contributors.yml`
Runs on each push to master branch. List the 5 most recently merged pull requests and extract their author. If any of the authors is a new one, updates the `.github/contributors.json`, regenerate the `CONTRIBUTORS.md` from it, and push back the changes to master.
#### Limitations
- If you merge a pull request from a new contributor, and merge another one right after, the push to master will fail as the remote will be out of date.
- If you merge more than 5 pull requests in a row like this, the new contributor might fail to be added.

View File

@ -4,30 +4,150 @@
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
SOURCEDIR = .
PAPER =
BUILDDIR = _build
.PHONY: help clean html livehtml linkcheck
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@awk '/^#/{c=substr($$0,3);next}c&&/^[[:alpha:]][[:alnum:]_-]+:/{print substr($$1,1,index($$1,":")),c}1{c=0}' $(MAKEFILE_LIST) | column -s: -t
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
# Clean the build output
clean:
-rm -rf $(BUILDDIR)/*
# Build the HTML docs
html:
$(SPHINXBUILD) -b html $(SPHINXOPTS) $(SOURCEDIR) $(BUILDDIR)/html
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
# Build and serve docs with live reload
livehtml:
sphinx-autobuild -b html --port 9000 --watch . -c . $(SOURCEDIR) $(BUILDDIR)/html
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/{{ cookiecutter.project_slug }}.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/{{ cookiecutter.project_slug }}.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/{{ cookiecutter.project_slug }}"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/{{ cookiecutter.project_slug }}"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
# Check all external links for integrity
linkcheck:
$(SPHINXBUILD) -b linkcheck $(SPHINXOPTS) $(SOURCEDIR) $(BUILDDIR)/linkcheck
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."

View File

@ -29,10 +29,7 @@ extensions = ["myst_parser"]
templates_path = ["_templates"]
# The suffix of source filenames.
source_suffix = {
".rst": "restructuredtext",
".md": "markdown",
}
source_suffix = [".rst", ".md"]
# The encoding of source files.
# source_encoding = 'utf-8-sig'
@ -188,7 +185,7 @@ latex_documents = [
"cookiecutter-django Documentation",
"cookiecutter-django",
"manual",
),
)
]
# The name of an image file (relative to this directory) to place at the top of
@ -223,7 +220,7 @@ man_pages = [
"Cookiecutter Django documentation",
["Daniel Roy Greenfeld"],
1,
),
)
]
# If true, show URL addresses after external links.
@ -242,7 +239,7 @@ texinfo_documents = [
"Cookiecutter Django documentation",
"Daniel Roy Greenfeld",
"Cookiecutter Django",
"A Cookiecutter template for creating production-ready Django projects quickly.",
"A Cookiecutter template for creating production-ready " "Django projects quickly.",
"Miscellaneous",
)
]

3
docs/contributing.md Normal file
View File

@ -0,0 +1,3 @@
```{include} ../CONTRIBUTING.md
```

View File

@ -12,9 +12,7 @@ Run these commands to deploy the project to Heroku:
heroku create --buildpack heroku/python
# Note: this is not a free plan
heroku addons:create heroku-postgresql:essential-0
heroku addons:create heroku-postgresql:mini
# On Windows use double quotes for the time zone, e.g.
# heroku pg:backups schedule --at "02:00 America/Los_Angeles" DATABASE_URL
heroku pg:backups schedule --at '02:00 America/Los_Angeles' DATABASE_URL
@ -25,6 +23,10 @@ Run these commands to deploy the project to Heroku:
# Assuming you chose Mailgun as mail service (see below for others)
heroku addons:create mailgun:starter
heroku config:set PYTHONHASHSEED=random
heroku config:set WEB_CONCURRENCY=4
heroku config:set DJANGO_DEBUG=False
heroku config:set DJANGO_SETTINGS_MODULE=config.settings.production
heroku config:set DJANGO_SECRET_KEY="$(openssl rand -base64 64)"
@ -44,7 +46,7 @@ Run these commands to deploy the project to Heroku:
# Assign with AWS_STORAGE_BUCKET_NAME
heroku config:set DJANGO_AWS_STORAGE_BUCKET_NAME=
git push heroku main
git push heroku master
heroku run python manage.py createsuperuser
@ -62,7 +64,7 @@ The script above assumes that you've chose Mailgun as email service. If you want
.. warning::
.. include:: ../includes/mailgun.rst
.. include:: mailgun.rst
Heroku & Docker
+++++++++++++++
@ -83,6 +85,8 @@ it's in the ``Procfile``, but is turned off by default:
.. code-block:: bash
# Set the broker URL to Redis
heroku config:set CELERY_BROKER_URL=`heroku config:get REDIS_URL`
# Scale dyno to 1 instance
heroku ps:scale worker=1

View File

@ -37,7 +37,7 @@ Make sure your project is fully committed and pushed up to Bitbucket or Github o
mkvirtualenv --python=/usr/bin/python3.10 my-project-name
pip install -r requirements/production.txt # may take a few minutes
.. note:: We're creating the virtualenv using Python 3.10 (``--python=/usr/bin/python3.10```), although Cookiecutter Django generates a project for Python 3.12. This is because, at time of writing, PythonAnywhere only supports Python 3.10. It shouldn't be a problem, but if is, you may try changing the Python version to 3.12 and see if it works. If it does, please let us know, or even better, submit a pull request to update this section.
.. note:: We're creating the virtualenv using Python 3.10 (``--python=/usr/bin/python3.10```), although Cookiecutter Django generates a project for Python 3.11. This is because, at time of writing, PythonAnywhere only supports Python 3.10. It shouldn't be a problem, but if is, you may try changing the Python version to 3.11 and see if it works. If it does, please let us know, or even better, submit a pull request to update this section.
Setting environment variables in the console
--------------------------------------------

View File

@ -14,7 +14,7 @@ Prerequisites
Understanding the Docker Compose Setup
--------------------------------------
Before you begin, check out the ``docker-compose.production.yml`` file in the root of this project. Keep note of how it provides configuration for the following services:
Before you begin, check out the ``production.yml`` file in the root of this project. Keep note of how it provides configuration for the following services:
* ``django``: your application running behind ``Gunicorn``;
* ``postgres``: PostgreSQL database with the application's relational data;
@ -55,7 +55,7 @@ You will probably also need to setup the Mail backend, for example by adding a `
.. warning::
.. include:: ../includes/mailgun.rst
.. include:: mailgun.rst
Optional: Use AWS IAM Role for EC2 instance
@ -107,7 +107,7 @@ To solve this, you can either:
2. create a ``.env`` file in the root of the project with just variables you need. You'll need to also define them in ``.envs/.production/.django`` (hence duplicating them).
3. set these variables when running the build command::
DJANGO_AWS_S3_CUSTOM_DOMAIN=example.com docker compose -f docker-compose.production.yml build``.
DJANGO_AWS_S3_CUSTOM_DOMAIN=example.com docker compose -f production.yml build``.
None of these options are ideal, we're open to suggestions on how to improve this. If you think you have one, please open an issue or a pull request.
@ -122,42 +122,42 @@ Building & Running Production Stack
You will need to build the stack first. To do that, run::
docker compose -f docker-compose.production.yml build
docker compose -f production.yml build
Once this is ready, you can run it with::
docker compose -f docker-compose.production.yml up
docker compose -f production.yml up
To run the stack and detach the containers, run::
docker compose -f docker-compose.production.yml up -d
docker compose -f production.yml up -d
To run a migration, open up a second terminal and run::
docker compose -f docker-compose.production.yml run --rm django python manage.py migrate
docker compose -f production.yml run --rm django python manage.py migrate
To create a superuser, run::
docker compose -f docker-compose.production.yml run --rm django python manage.py createsuperuser
docker compose -f production.yml run --rm django python manage.py createsuperuser
If you need a shell, run::
docker compose -f docker-compose.production.yml run --rm django python manage.py shell
docker compose -f production.yml run --rm django python manage.py shell
To check the logs out, run::
docker compose -f docker-compose.production.yml logs
docker compose -f production.yml logs
If you want to scale your application, run::
docker compose -f docker-compose.production.yml up --scale django=4
docker compose -f docker-compose.production.yml up --scale celeryworker=2
docker compose -f production.yml up --scale django=4
docker compose -f production.yml up --scale celeryworker=2
.. warning:: don't try to scale ``postgres``, ``celerybeat``, or ``traefik``.
To see how your containers are doing run::
docker compose -f docker-compose.production.yml ps
docker compose -f production.yml ps
Example: Supervisor
@ -165,12 +165,12 @@ Example: Supervisor
Once you are ready with your initial setup, you want to make sure that your application is run by a process manager to
survive reboots and auto restarts in case of an error. You can use the process manager you are most familiar with. All
it needs to do is to run ``docker compose -f docker-compose.production.yml up`` in your projects root directory.
it needs to do is to run ``docker compose -f production.yml up`` in your projects root directory.
If you are using ``supervisor``, you can use this file as a starting point::
[program:{{cookiecutter.project_slug}}]
command=docker compose -f docker-compose.production.yml up
command=docker compose -f production.yml up
directory=/path/to/{{cookiecutter.project_slug}}
redirect_stderr=true
autostart=true

View File

@ -32,9 +32,9 @@ Build the Stack
This can take a while, especially the first time you run this particular command on your development system::
$ docker compose -f docker-compose.local.yml build
$ docker compose -f local.yml build
Generally, if you want to emulate production environment use ``docker-compose.production.yml`` instead. And this is true for any other actions you might need to perform: whenever a switch is required, just do it!
Generally, if you want to emulate production environment use ``production.yml`` instead. And this is true for any other actions you might need to perform: whenever a switch is required, just do it!
Before doing any git commit, `pre-commit`_ should be installed globally on your local machine, and then::
@ -43,6 +43,7 @@ Before doing any git commit, `pre-commit`_ should be installed globally on your
Failing to do so will result with a bunch of CI and Linter errors that can be avoided with pre-commit.
Run the Stack
-------------
@ -50,11 +51,11 @@ This brings up both Django and PostgreSQL. The first time it is run it might tak
Open a terminal at the project root and run the following for local development::
$ docker compose -f docker-compose.local.yml up
$ docker compose -f local.yml up
You can also set the environment variable ``COMPOSE_FILE`` pointing to ``docker-compose.local.yml`` like this::
You can also set the environment variable ``COMPOSE_FILE`` pointing to ``local.yml`` like this::
$ export COMPOSE_FILE=docker-compose.local.yml
$ export COMPOSE_FILE=local.yml
And then run::
@ -64,23 +65,16 @@ To run in a detached (background) mode, just::
$ docker compose up -d
These commands don't run the docs service. In order to run docs service you can run::
$ docker compose -f docker-compose.docs.yml up
To run the docs with local services just use::
$ docker compose -f docker-compose.local.yml -f docker-compose.docs.yml up
The site should start and be accessible at http://localhost:3000 if you selected Webpack or Gulp as frontend pipeline and http://localhost:8000 otherwise.
Execute Management Commands
---------------------------
As with any shell command that we wish to run in our container, this is done using the ``docker compose -f docker-compose.local.yml run --rm`` command: ::
As with any shell command that we wish to run in our container, this is done using the ``docker compose -f local.yml run --rm`` command: ::
$ docker compose -f docker-compose.local.yml run --rm django python manage.py migrate
$ docker compose -f docker-compose.local.yml run --rm django python manage.py createsuperuser
$ docker compose -f local.yml run --rm django python manage.py migrate
$ docker compose -f local.yml run --rm django python manage.py createsuperuser
Here, ``django`` is the target service we are executing the commands against.
Also, please note that the ``docker exec`` does not work for running management commands.
@ -90,12 +84,13 @@ Also, please note that the ``docker exec`` does not work for running management
When ``DEBUG`` is set to ``True``, the host is validated against ``['localhost', '127.0.0.1', '[::1]']``. This is adequate when running a ``virtualenv``. For Docker, in the ``config.settings.local``, add your host development server IP to ``INTERNAL_IPS`` or ``ALLOWED_HOSTS`` if the variable exists.
.. _envs:
Configuring the Environment
---------------------------
This is the excerpt from your project's ``docker-compose.local.yml``: ::
This is the excerpt from your project's ``local.yml``: ::
# ...
@ -115,8 +110,8 @@ The most important thing for us here now is ``env_file`` section enlisting ``./.
.envs
├── .local
├── .django
└── .postgres
   ├── .django
   └── .postgres
└── .production
├── .django
└── .postgres
@ -161,8 +156,8 @@ You have to modify the relevant requirement file: base, local or production by a
To get this change picked up, you'll need to rebuild the image(s) and restart the running container: ::
docker compose -f docker-compose.local.yml build
docker compose -f docker-compose.local.yml up
docker compose -f local.yml build
docker compose -f local.yml up
Debugging
~~~~~~~~~
@ -176,7 +171,7 @@ If you are using the following within your code to debug: ::
Then you may need to run the following for it to work as desired: ::
$ docker compose -f docker-compose.local.yml run --rm --service-ports django
$ docker compose -f local.yml run --rm --service-ports django
django-debug-toolbar
@ -193,6 +188,7 @@ The ``container_name`` from the yml file can be used to check on containers with
$ docker logs <project_slug>_local_celeryworker
$ docker top <project_slug>_local_celeryworker
Notice that the ``container_name`` is generated dynamically using your project slug as a prefix
Mailpit
@ -228,7 +224,7 @@ Prerequisites:
* ``use_docker`` was set to ``y`` on project initialization;
* ``use_celery`` was set to ``y`` on project initialization.
By default, it's enabled both in local and production environments (``docker-compose.local.yml`` and ``docker-compose.production.yml`` Docker Compose configs, respectively) through a ``flower`` service. For added security, ``flower`` requires its clients to provide authentication credentials specified as the corresponding environments' ``.envs/.local/.django`` and ``.envs/.production/.django`` ``CELERY_FLOWER_USER`` and ``CELERY_FLOWER_PASSWORD`` environment variables. Check out ``localhost:5555`` and see for yourself.
By default, it's enabled both in local and production environments (``local.yml`` and ``production.yml`` Docker Compose configs, respectively) through a ``flower`` service. For added security, ``flower`` requires its clients to provide authentication credentials specified as the corresponding environments' ``.envs/.local/.django`` and ``.envs/.production/.django`` ``CELERY_FLOWER_USER`` and ``CELERY_FLOWER_PASSWORD`` environment variables. Check out ``localhost:5555`` and see for yourself.
.. _`Flower`: https://github.com/mher/flower
@ -242,65 +238,46 @@ The stack comes with a dedicated node service to build the static assets, watch
.. _Sass: https://sass-lang.com/
.. _live reloading: https://browsersync.io
Developing locally with HTTPS
-----------------------------
Using Just for Docker Commands
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Increasingly it is becoming necessary to develop software in a secure environment in order that there are very few changes when deploying to production. Recently Facebook changed their policies for apps/sites that use Facebook login which requires the use of an HTTPS URL for the OAuth redirect URL. So if you want to use the ``users`` application with a OAuth provider such as Facebook, securing your communication to the local development environment will be necessary.
We have included a ``justfile`` to simplify the use of frequent Docker commands for local development.
In order to create a secure environment, we need to have a trusted SSL certificate installed in our Docker application.
.. warning::
Currently, "Just" does not reliably handle signals or forward them to its subprocesses. As a result,
pressing CTRL+C (or sending other signals like SIGTERM, SIGINT, or SIGHUP) may only interrupt
"Just" itself rather than its subprocesses.
For more information, see `this GitHub issue <https://github.com/casey/just/issues/2473>`_.
#. **Let's Encrypt**
First, install Just using one of the methods described in the `official documentation <https://just.systems/man/en/packages.html>`_.
The official line from Lets Encrypt is:
Here are the available commands:
[For local development section] ... The best option: Generate your own certificate, either self-signed or signed by a local root, and trust it in your operating systems trust store. Then use that certificate in your local web server. See below for details.
- ``just build``
Builds the Python image using the local Docker Compose file.
See `letsencrypt.org - certificates-for-localhost`_
- ``just up``
Starts the containers in detached mode and removes orphaned containers.
.. _`letsencrypt.org - certificates-for-localhost`: https://letsencrypt.org/docs/certificates-for-localhost/
- ``just down``
Stops the running containers.
#. **mkcert: Valid Https Certificates For Localhost**
- ``just prune``
Stops and removes containers along with their volumes. You can optionally pass an argument with the service name to prune a single container.
`mkcert`_ is a simple by design tool that hides all the arcane knowledge required to generate valid TLS certificates. It works for any hostname or IP, including localhost. It supports macOS, Linux, and Windows, and Firefox, Chrome and Java. It even works on mobile devices with a couple manual steps.
- ``just logs``
Shows container logs. You can optionally pass an argument with the service name to view logs for a specific service.
See https://blog.filippo.io/mkcert-valid-https-certificates-for-localhost/
- ``just manage <command>``
Runs Django management commands within the container. Replace ``<command>`` with any valid Django management command, such as ``migrate``, ``createsuperuser``, or ``shell``.
.. _`mkcert`: https://github.com/FiloSottile/mkcert/blob/master/README.md#supported-root-stores
After installing a trusted TLS certificate, configure your docker installation. We are going to configure an ``nginx`` reverse-proxy server. This makes sure that it does not interfere with our ``traefik`` configuration that is reserved for production environments.
(Optionally) Developing locally with HTTPS
------------------------------------------
These are the places that you should configure to secure your local environment.
Nginx
certs
~~~~~
If you want to add some sort of social authentication with a OAuth provider such as Facebook, securing your communication to the local development environment will be necessary. These providers usually require that you use an HTTPS URL for the OAuth redirect URL for the Facebook login to work appropriately.
Take the certificates that you generated and place them in a folder called ``certs`` in the project's root folder. Assuming that you registered your local hostname as ``my-dev-env.local``, the certificates you will put in the folder should have the names ``my-dev-env.local.crt`` and ``my-dev-env.local.key``.
Here is a link to an article on `how to add HTTPS using Nginx`_ to your local docker installation. This also includes how to serve files from the ``media`` location, in the event that you are want to serve user-uploaded content.
local.yml
~~~~~~~~~
.. _`how to add HTTPS using Nginx`: https://afroshok.com/cookiecutter-https
#. Add the ``nginx-proxy`` service. ::
Webpack
~~~~~~~
If you are using Webpack, first install `mkcert`_. It is a simple by design tool that hides all the arcane knowledge required to generate valid TLS certificates. It works for any hostname or IP, including localhost. It supports macOS, Linux, and Windows, and Firefox, Chrome and Java. It even works on mobile devices with a couple manual steps. See https://blog.filippo.io/mkcert-valid-https-certificates-for-localhost/
.. _`mkcert`: https://github.com/FiloSottile/mkcert/blob/master/README.md#supported-root-stores
These are the places that you should configure to secure your local environment. Take the certificates that you generated and place them in a folder called ``certs`` in the project's root folder. Configure an ``nginx`` reverse-proxy server as a ``service`` in the ``docker-compose.local.yml``. This makes sure that it does not interfere with our ``traefik`` configuration that is reserved for production environments.
Assuming that you registered your local hostname as ``my-dev-env.local``, the certificates you will put in the folder should have the names ``my-dev-env.local.crt`` and ``my-dev-env.local.key``.
1. Add the ``nginx-proxy`` service to the ``docker-compose.local.yml``. ::
...
nginx-proxy:
image: jwilder/nginx-proxy:alpine
@ -313,28 +290,66 @@ Assuming that you registered your local hostname as ``my-dev-env.local``, the ce
- ./certs:/etc/nginx/certs
restart: always
depends_on:
- node
environment:
- VIRTUAL_HOST=my-dev-env.local
- VIRTUAL_PORT=3000
- django
2. Add the local secure domain to the ``config/settings/local.py``. You should allow the new hostname ::
...
ALLOWED_HOSTS = ["localhost", "0.0.0.0", "127.0.0.1", "my-dev-env.local"]
#. Link the ``nginx-proxy`` to ``django`` through environment variables.
3. Add the following configuration to the ``devServer`` section of ``webpack/dev.config.js`` ::
``django`` already has an ``.env`` file connected to it. Add the following variables. You should do this especially if you are working with a team and you want to keep your local environment details to yourself.
client: {
webSocketURL: 'auto://0.0.0.0:0/ws', // note the `:0` after `0.0.0.0`
},
::
# HTTPS
# ------------------------------------------------------------------------------
VIRTUAL_HOST=my-dev-env.local
VIRTUAL_PORT=8000
The services run behind the reverse proxy.
config/settings/local.py
~~~~~~~~~~~~~~~~~~~~~~~~
You should allow the new hostname. ::
ALLOWED_HOSTS = ["localhost", "0.0.0.0", "127.0.0.1", "my-dev-env.local"]
Rebuild your ``docker`` application. ::
$ docker compose -f docker-compose.local.yml up -d --build
$ docker compose -f local.yml up -d --build
Go to your browser and type in your URL bar ``https://my-dev-env.local``.
Go to your browser and type in your URL bar ``https://my-dev-env.local``
For more on this configuration, see `https with nginx`_.
See `https with nginx`_ for more information on this configuration.
.. _`https with nginx`: https://codewithhugo.com/docker-compose-local-https/
.. _`https with nginx`: https://codewithhugo.com/docker-compose-local-https/
.gitignore
~~~~~~~~~~
Add ``certs/*`` to the ``.gitignore`` file. This allows the folder to be included in the repo but its contents to be ignored.
*This configuration is for local development environments only. Do not use this for production since you might expose your local* ``rootCA-key.pem``.
Webpack
~~~~~~~
If you are using Webpack:
1. On the ``nginx-proxy`` service in ``local.yml``, change ``depends_on`` to ``node`` instead of ``django``.
2. On the ``node`` service in ``local.yml``, add the following environment configuration:
::
environment:
- VIRTUAL_HOST=my-dev-env.local
- VIRTUAL_PORT=3000
3. Add the following configuration to the ``devServer`` section of ``webpack/dev.config.js``:
::
client: {
webSocketURL: 'auto://0.0.0.0:0/ws', // note the `:0` after `0.0.0.0`
},

View File

@ -9,7 +9,7 @@ Setting Up Development Environment
Make sure to have the following on your host:
* Python 3.12
* Python 3.11
* PostgreSQL_.
* Redis_, if using Celery
* Cookiecutter_
@ -18,13 +18,14 @@ First things first.
#. Create a virtualenv: ::
$ python3.12 -m venv <virtual env path>
$ python3.11 -m venv <virtual env path>
#. Activate the virtualenv you have just created: ::
$ source <virtual env path>/bin/activate
#. .. include:: generate-project-block.rst
#.
.. include:: generate-project-block.rst
#. Install development requirements: ::
@ -55,6 +56,8 @@ First things first.
#. Set the environment variables for your database(s): ::
$ export DATABASE_URL=postgres://postgres:<password>@127.0.0.1:5432/<DB name given to createdb>
# Optional: set broker URL if using Celery
$ export CELERY_BROKER_URL=redis://localhost:6379/0
.. note::
@ -93,61 +96,6 @@ First things first.
.. _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: ::
$ 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
-------------------
@ -216,7 +164,7 @@ The project comes with a simple task for manual testing purposes, inside `<proje
You can also use Django admin to queue up tasks, thanks to the `django-celerybeat`_ package.
.. _Getting started with Redis: https://redis.io/docs/getting-started/
.. _Getting started with Redis guide: https://redis.io/docs/getting-started/
.. _Celery Workers Guide: https://docs.celeryq.dev/en/stable/userguide/workers.html
.. _django-celerybeat: https://django-celery-beat.readthedocs.io/en/latest/

View File

@ -1,14 +1,14 @@
PostgreSQL Backups with Docker
==============================
.. note:: For brevity it is assumed that you will be running the below commands against local environment, however, this is by no means mandatory so feel free to switch to ``docker-compose.production.yml`` when needed.
.. note:: For brevity it is assumed that you will be running the below commands against local environment, however, this is by no means mandatory so feel free to switch to ``production.yml`` when needed.
Prerequisites
-------------
#. the project was generated with ``use_docker`` set to ``y``;
#. the stack is up and running: ``docker compose -f docker-compose.local.yml up -d postgres``.
#. the stack is up and running: ``docker compose -f local.yml up -d postgres``.
Creating a Backup
@ -16,7 +16,7 @@ Creating a Backup
To create a backup, run::
$ docker compose -f docker-compose.local.yml exec postgres backup
$ docker compose -f local.yml exec postgres backup
Assuming your project's database is named ``my_project`` here is what you will see: ::
@ -31,7 +31,7 @@ Viewing the Existing Backups
To list existing backups, ::
$ docker compose -f docker-compose.local.yml exec postgres backups
$ docker compose -f local.yml exec postgres backups
These are the sample contents of ``/backups``: ::
@ -55,9 +55,9 @@ With a single backup file copied to ``.`` that would be ::
$ docker cp 9c5c3f055843:/backups/backup_2018_03_13T09_05_07.sql.gz .
You can also get the container ID using ``docker compose -f docker-compose.local.yml ps -q postgres`` so if you want to automate your backups, you don't have to check the container ID manually every time. Here is the full command ::
You can also get the container ID using ``docker compose -f local.yml ps -q postgres`` so if you want to automate your backups, you don't have to check the container ID manually every time. Here is the full command ::
$ docker cp $(docker compose -f docker-compose.local.yml ps -q postgres):/backups ./backups
$ docker cp $(docker compose -f local.yml ps -q postgres):/backups ./backups
.. _`command`: https://docs.docker.com/engine/reference/commandline/cp/
@ -66,7 +66,7 @@ Restoring from the Existing Backup
To restore from one of the backups you have already got (take the ``backup_2018_03_13T09_05_07.sql.gz`` for example), ::
$ docker compose -f docker-compose.local.yml exec postgres restore backup_2018_03_13T09_05_07.sql.gz
$ docker compose -f local.yml exec postgres restore backup_2018_03_13T09_05_07.sql.gz
You will see something like ::
@ -95,33 +95,12 @@ Backup to Amazon S3
For uploading your backups to Amazon S3 you can use the aws cli container. There is an upload command for uploading the postgres /backups directory recursively and there is a download command for downloading a specific backup. The default S3 environment variables are used. ::
$ docker compose -f docker-compose.production.yml run --rm awscli upload
$ docker compose -f docker-compose.production.yml run --rm awscli download backup_2018_03_13T09_05_07.sql.gz
$ docker compose -f production.yml run --rm awscli upload
$ docker compose -f production.yml run --rm awscli download backup_2018_03_13T09_05_07.sql.gz
Remove Backup
----------------------------------
To remove backup you can use the ``rmbackup`` command. This will remove the backup from the ``/backups`` directory. ::
$ docker compose -f docker-compose.local.yml exec postgres rmbackup backup_2018_03_13T09_05_07.sql.gz
Upgrading PostgreSQL
----------------------------------
Upgrading PostgreSQL in your project requires a series of carefully executed steps. Start by halting all containers, excluding the postgres container. Following this, create a backup and proceed to remove the outdated data volume. ::
$ docker compose -f docker-compose.local.yml down
$ docker compose -f docker-compose.local.yml up -d postgres
$ docker compose -f docker-compose.local.yml run --rm postgres backup
$ docker compose -f docker-compose.local.yml down
$ docker volume rm my_project_postgres_data
.. note:: Neglecting to remove the old data volume may lead to issues, such as the new postgres container failing to start with errors like ``FATAL: database files are incompatible with server``, and ``could not translate host name "postgres" to address: Name or service not known``.
To complete the upgrade, update the PostgreSQL version in the corresponding Dockerfile (e.g. ``compose/production/postgres/Dockerfile``) and build a new version of PostgreSQL. ::
$ docker compose -f docker-compose.local.yml build postgres
$ docker compose -f docker-compose.local.yml up -d postgres
$ docker compose -f docker-compose.local.yml run --rm postgres restore backup_2018_03_13T09_05_07.sql.gz
$ docker compose -f docker-compose.local.yml up -d
$ docker compose -f local.yml exec postgres rmbackup backup_2018_03_13T09_05_07.sql.gz

View File

@ -11,7 +11,7 @@ After you have set up to `develop locally`_, run the following command from the
If you set up your project to `develop locally with docker`_, run the following command: ::
$ docker compose -f docker-compose.docs.yml up
$ docker compose -f local.yml up docs
Navigate to port 9000 on your host to see the documentation. This will be opened automatically at `localhost`_ for local, non-docker development.

View File

@ -22,6 +22,6 @@ TODO
Why doesn't this follow the layout from Two Scoops of Django?
-------------------------------------------------------------
You may notice that some elements of this project do not exactly match what we describe in chapter 3 of `Two Scoops of Django 3.x`_. 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.
You may notice that some elements of this project do not exactly match what we describe in chapter 3 of `Two Scoops of Django 1.11`_. 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.
.. _Two Scoops of Django 3.x: https://www.feldroy.com/two-scoops-press#two-scoops-of-django
.. _Two Scoops of Django 1.11: https://www.feldroy.com/collections/django/products/two-scoops-of-django-1-11

View File

@ -7,51 +7,27 @@ Powered by Cookiecutter_, Cookiecutter Django is a project template for jumpstar
.. _cookiecutter: https://github.com/cookiecutter/cookiecutter
.. toctree::
:maxdepth: 2
:caption: Getting Started
1-getting-started/project-generation-options
1-getting-started/settings
Contents
--------
.. toctree::
:maxdepth: 2
:caption: Local Development
2-local-development/developing-locally
2-local-development/developing-locally-docker
.. toctree::
:maxdepth: 2
:caption: Deployment
3-deployment/deployment-on-pythonanywhere
3-deployment/deployment-on-heroku
3-deployment/deployment-with-docker
.. toctree::
:maxdepth: 2
:caption: Guides
4-guides/docker-postgres-backups
4-guides/linters
4-guides/testing
4-guides/document
4-guides/websocket
.. toctree::
:maxdepth: 2
:caption: Help
5-help/faq
5-help/troubleshooting
.. toctree::
:maxdepth: 2
:caption: About
6-about/contributing
6-about/maintainer-guide
project-generation-options
developing-locally
developing-locally-docker
settings
linters
testing
document
deployment-on-pythonanywhere
deployment-on-heroku
deployment-with-docker
docker-postgres-backups
websocket
faq
troubleshooting
contributing
Indices and tables
------------------

View File

@ -5,20 +5,36 @@ REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=.
set BUILDDIR=_build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS%
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
set I18NSPHINXOPTS=%SPHINXOPTS% .
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^<target^>` where ^<target^> is one of
echo. clean to clean the build directory
echo. html to make standalone HTML files
echo. livehtml to build and serve docs with live reload
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
goto end
)
@ -29,22 +45,132 @@ if "%1" == "clean" (
)
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %SOURCEDIR% %BUILDDIR%/html
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "livehtml" (
sphinx-autobuild -b html --port 9000 --watch . -c . %SOURCEDIR% %BUILDDIR%/html
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\{{ cookiecutter.project_slug }}.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\{{ cookiecutter.project_slug }}.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %SOURCEDIR% %BUILDDIR%/linkcheck
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
@ -52,4 +178,13 @@ or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
:end

View File

@ -66,10 +66,12 @@ use_docker:
postgresql_version:
Select a PostgreSQL_ version to use. The choices are:
1. 16
2. 15
3. 14
4. 13
1. 15
2. 14
3. 13
4. 12
5. 11
6. 10
cloud_provider:
Select a cloud provider for static & media files. The choices are:
@ -90,7 +92,7 @@ mail_service:
4. Mandrill_
5. Postmark_
6. SendGrid_
7. `Brevo (formerly SendinBlue)`_
7. SendinBlue_
8. SparkPost_
9. `Other SMTP`_
@ -173,7 +175,7 @@ debug:
.. _Mandrill: http://mandrill.com
.. _Postmark: https://postmarkapp.com
.. _SendGrid: https://sendgrid.com
.. _Brevo (formerly SendinBlue): https://www.brevo.com
.. _SendinBlue: https://www.sendinblue.com
.. _SparkPost: https://www.sparkpost.com
.. _Other SMTP: https://anymail.readthedocs.io/en/stable/

3
docs/requirements.txt Normal file
View File

@ -0,0 +1,3 @@
sphinx==7.2.6
sphinx-rtd-theme==2.0.0
myst-parser==2.0.0

View File

@ -39,6 +39,7 @@ The following table lists settings and their defaults for third-party applicatio
======================================= =========================== ============================================== ======================================================================
Environment Variable Django Setting Development Default Production Default
======================================= =========================== ============================================== ======================================================================
CELERY_BROKER_URL CELERY_BROKER_URL auto w/ Docker; raises error w/o raises error
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
@ -68,8 +69,8 @@ SENDGRID_API_KEY SENDGRID_API_KEY n/a
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/"
SENDINBLUE_API_KEY SENDINBLUE_API_KEY n/a raises error
SENDINBLUE_API_URL n/a n/a "https://api.sendinblue.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"
======================================= =========================== ============================================== ======================================================================

View File

@ -19,7 +19,7 @@ You will get a readout of the `users` app that has already been set up with test
If you set up your project to `develop locally with docker`_, run the following command: ::
$ docker compose -f docker-compose.local.yml run --rm django pytest
$ docker compose -f local.yml run --rm django pytest
Targeting particular apps for testing in ``docker`` follows a similar pattern as previously shown above.
@ -36,8 +36,8 @@ Once the tests are complete, in order to see the code coverage, run the followin
If you're running the project locally with Docker, use these commands instead: ::
$ docker compose -f docker-compose.local.yml run --rm django coverage run -m pytest
$ docker compose -f docker-compose.local.yml run --rm django coverage report
$ docker compose -f local.yml run --rm django coverage run -m pytest
$ docker compose -f local.yml run --rm django coverage report
.. note::

View File

@ -8,7 +8,7 @@ Server Error on sign-up/log-in
Make sure you have configured the mail backend (e.g. Mailgun) by adding the API key and sender domain
.. include:: ../includes/mailgun.rst
.. include:: mailgun.rst
.. _docker-postgres-auth-failed:
@ -30,7 +30,7 @@ If you recreate the project multiple times with the same name, Docker would pres
To fix this, you can either:
- Clear your project-related Docker cache with ``docker compose -f docker-compose.local.yml down --volumes --rmi all``.
- Clear your project-related Docker cache with ``docker compose -f local.yml down --volumes --rmi all``.
- Use the Docker volume sub-commands to find volumes (`ls`_) and remove them (`rm`_).
- Use the `prune`_ command to clear system-wide (use with care!).

View File

@ -1,8 +1,21 @@
"""
NOTE:
the below code is to be maintained Python 2.x-compatible
as the whole Cookiecutter Django project initialization
can potentially be run in Python 2.x environment
(at least so we presume in `pre_gen_project.py`).
TODO: restrict Cookiecutter Django project initialization to
Python 3.x environments only
"""
from __future__ import print_function
import json
import os
import random
import shutil
import string
from pathlib import Path
try:
# Inspired by
@ -24,28 +37,40 @@ DEBUG_VALUE = "debug"
def remove_open_source_files():
file_names = ["CONTRIBUTORS.txt", "LICENSE"]
for file_name in file_names:
Path(file_name).unlink()
os.remove(file_name)
def remove_gplv3_files():
file_names = ["COPYING"]
for file_name in file_names:
Path(file_name).unlink()
os.remove(file_name)
def remove_custom_user_manager_files():
users_path = Path("{{cookiecutter.project_slug}}", "users")
(users_path / "managers.py").unlink()
(users_path / "tests" / "test_managers.py").unlink()
os.remove(
os.path.join(
"{{cookiecutter.project_slug}}",
"users",
"managers.py",
)
)
os.remove(
os.path.join(
"{{cookiecutter.project_slug}}",
"users",
"tests",
"test_managers.py",
)
)
def remove_pycharm_files():
idea_dir_path = Path(".idea")
if idea_dir_path.exists():
idea_dir_path = ".idea"
if os.path.exists(idea_dir_path):
shutil.rmtree(idea_dir_path)
docs_dir_path = Path("docs", "pycharm")
if docs_dir_path.exists():
docs_dir_path = os.path.join("docs", "pycharm")
if os.path.exists(docs_dir_path):
shutil.rmtree(docs_dir_path)
@ -53,22 +78,13 @@ def remove_docker_files():
shutil.rmtree(".devcontainer")
shutil.rmtree("compose")
file_names = [
"docker-compose.local.yml",
"docker-compose.production.yml",
".dockerignore",
"justfile",
]
file_names = ["local.yml", "production.yml", ".dockerignore"]
for file_name in file_names:
Path(file_name).unlink()
os.remove(file_name)
if "{{ cookiecutter.editor }}" == "PyCharm":
file_names = ["docker_compose_up_django.xml", "docker_compose_up_docs.xml"]
for file_name in file_names:
Path(".idea", "runConfigurations", file_name).unlink()
def remove_nginx_docker_files():
shutil.rmtree(Path("compose", "production", "nginx"))
os.remove(os.path.join(".idea", "runConfigurations", file_name))
def remove_utility_files():
@ -76,23 +92,23 @@ def remove_utility_files():
def remove_heroku_files():
file_names = ["Procfile", "requirements.txt"]
file_names = ["Procfile", "runtime.txt", "requirements.txt"]
for file_name in file_names:
if file_name == "requirements.txt" and "{{ cookiecutter.ci_tool }}".lower() == "travis":
# don't remove the file if we are using travisci but not using heroku
continue
Path(file_name).unlink()
os.remove(file_name)
shutil.rmtree("bin")
def remove_sass_files():
shutil.rmtree(Path("{{cookiecutter.project_slug}}", "static", "sass"))
shutil.rmtree(os.path.join("{{cookiecutter.project_slug}}", "static", "sass"))
def remove_gulp_files():
file_names = ["gulpfile.mjs"]
file_names = ["gulpfile.js"]
for file_name in file_names:
Path(file_name).unlink()
os.remove(file_name)
def remove_webpack_files():
@ -101,30 +117,36 @@ def remove_webpack_files():
def remove_vendors_js():
vendors_js_path = Path("{{ cookiecutter.project_slug }}", "static", "js", "vendors.js")
if vendors_js_path.exists():
vendors_js_path.unlink()
vendors_js_path = os.path.join(
"{{ cookiecutter.project_slug }}",
"static",
"js",
"vendors.js",
)
if os.path.exists(vendors_js_path):
os.remove(vendors_js_path)
def remove_packagejson_file():
file_names = ["package.json"]
for file_name in file_names:
Path(file_name).unlink()
os.remove(file_name)
def update_package_json(remove_dev_deps=None, remove_keys=None, scripts=None):
remove_dev_deps = remove_dev_deps or []
remove_keys = remove_keys or []
scripts = scripts or {}
package_json = Path("package.json")
content = json.loads(package_json.read_text())
with open("package.json", mode="r") as fd:
content = json.load(fd)
for package_name in remove_dev_deps:
content["devDependencies"].pop(package_name)
for key in remove_keys:
content.pop(key)
content["scripts"].update(scripts)
updated_content = json.dumps(content, ensure_ascii=False, indent=2) + "\n"
package_json.write_text(updated_content)
with open("package.json", mode="w") as fd:
json.dump(content, fd, ensure_ascii=False, indent=2)
fd.write("\n")
def handle_js_runner(choice, use_docker, use_async):
@ -149,7 +171,7 @@ def handle_js_runner(choice, use_docker, use_async):
remove_keys=["babel"],
scripts={
"dev": "gulp",
"build": "gulp build",
"build": "gulp generate-assets",
},
)
remove_webpack_files()
@ -188,8 +210,8 @@ def handle_js_runner(choice, use_docker, use_async):
def remove_prettier_pre_commit():
pre_commit_yaml = Path(".pre-commit-config.yaml")
content = pre_commit_yaml.read_text().splitlines()
with open(".pre-commit-config.yaml", "r") as fd:
content = fd.readlines()
removing = False
new_lines = []
@ -201,34 +223,35 @@ def remove_prettier_pre_commit():
if not removing:
new_lines.append(line)
pre_commit_yaml.write_text("\n".join(new_lines))
with open(".pre-commit-config.yaml", "w") as fd:
fd.writelines(new_lines)
def remove_celery_files():
file_paths = [
Path("config", "celery_app.py"),
Path("{{ cookiecutter.project_slug }}", "users", "tasks.py"),
Path("{{ cookiecutter.project_slug }}", "users", "tests", "test_tasks.py"),
file_names = [
os.path.join("config", "celery_app.py"),
os.path.join("{{ cookiecutter.project_slug }}", "users", "tasks.py"),
os.path.join("{{ cookiecutter.project_slug }}", "users", "tests", "test_tasks.py"),
]
for file_path in file_paths:
file_path.unlink()
for file_name in file_names:
os.remove(file_name)
def remove_async_files():
file_paths = [
Path("config", "asgi.py"),
Path("config", "websocket.py"),
file_names = [
os.path.join("config", "asgi.py"),
os.path.join("config", "websocket.py"),
]
for file_path in file_paths:
file_path.unlink()
for file_name in file_names:
os.remove(file_name)
def remove_dottravisyml_file():
Path(".travis.yml").unlink()
os.remove(".travis.yml")
def remove_dotgitlabciyml_file():
Path(".gitlab-ci.yml").unlink()
os.remove(".gitlab-ci.yml")
def remove_dotgithub_folder():
@ -236,7 +259,7 @@ def remove_dotgithub_folder():
def remove_dotdrone_file():
Path(".drone.yml").unlink()
os.remove(".drone.yml")
def generate_random_string(length, using_digits=False, using_ascii_letters=False, using_punctuation=False):
@ -262,7 +285,7 @@ def generate_random_string(length, using_digits=False, using_ascii_letters=False
return "".join([random.choice(symbols) for _ in range(length)])
def set_flag(file_path: Path, flag, value=None, formatted=None, *args, **kwargs):
def set_flag(file_path, flag, value=None, formatted=None, *args, **kwargs):
if value is None:
random_string = generate_random_string(*args, **kwargs)
if random_string is None:
@ -275,7 +298,7 @@ def set_flag(file_path: Path, flag, value=None, formatted=None, *args, **kwargs)
random_string = formatted.format(random_string)
value = random_string
with file_path.open("r+") as f:
with open(file_path, "r+") as f:
file_contents = f.read().replace(flag, value)
f.seek(0)
f.write(file_contents)
@ -284,7 +307,7 @@ def set_flag(file_path: Path, flag, value=None, formatted=None, *args, **kwargs)
return value
def set_django_secret_key(file_path: Path):
def set_django_secret_key(file_path):
django_secret_key = set_flag(
file_path,
"!!!SET DJANGO_SECRET_KEY!!!",
@ -295,7 +318,7 @@ def set_django_secret_key(file_path: Path):
return django_secret_key
def set_django_admin_url(file_path: Path):
def set_django_admin_url(file_path):
django_admin_url = set_flag(
file_path,
"!!!SET DJANGO_ADMIN_URL!!!",
@ -350,16 +373,16 @@ def set_celery_flower_password(file_path, value=None):
def append_to_gitignore_file(ignored_line):
with Path(".gitignore").open("a") as gitignore_file:
with open(".gitignore", "a") as gitignore_file:
gitignore_file.write(ignored_line)
gitignore_file.write("\n")
def set_flags_in_envs(postgres_user, celery_flower_user, debug=False):
local_django_envs_path = Path(".envs", ".local", ".django")
production_django_envs_path = Path(".envs", ".production", ".django")
local_postgres_envs_path = Path(".envs", ".local", ".postgres")
production_postgres_envs_path = Path(".envs", ".production", ".postgres")
local_django_envs_path = os.path.join(".envs", ".local", ".django")
production_django_envs_path = os.path.join(".envs", ".production", ".django")
local_postgres_envs_path = os.path.join(".envs", ".local", ".postgres")
production_postgres_envs_path = os.path.join(".envs", ".production", ".postgres")
set_django_secret_key(production_django_envs_path)
set_django_admin_url(production_django_envs_path)
@ -376,33 +399,35 @@ def set_flags_in_envs(postgres_user, celery_flower_user, debug=False):
def set_flags_in_settings_files():
set_django_secret_key(Path("config", "settings", "local.py"))
set_django_secret_key(Path("config", "settings", "test.py"))
set_django_secret_key(os.path.join("config", "settings", "local.py"))
set_django_secret_key(os.path.join("config", "settings", "test.py"))
def remove_envs_and_associated_files():
shutil.rmtree(".envs")
Path("merge_production_dotenvs_in_dotenv.py").unlink()
os.remove("merge_production_dotenvs_in_dotenv.py")
shutil.rmtree("tests")
def remove_celery_compose_dirs():
shutil.rmtree(Path("compose", "local", "django", "celery"))
shutil.rmtree(Path("compose", "production", "django", "celery"))
shutil.rmtree(os.path.join("compose", "local", "django", "celery"))
shutil.rmtree(os.path.join("compose", "production", "django", "celery"))
def remove_node_dockerfile():
shutil.rmtree(Path("compose", "local", "node"))
shutil.rmtree(os.path.join("compose", "local", "node"))
def remove_aws_dockerfile():
shutil.rmtree(Path("compose", "production", "aws"))
shutil.rmtree(os.path.join("compose", "production", "aws"))
def remove_drf_starter_files():
Path("config", "api_router.py").unlink()
shutil.rmtree(Path("{{cookiecutter.project_slug}}", "users", "api"))
shutil.rmtree(Path("{{cookiecutter.project_slug}}", "users", "tests", "api"))
os.remove(os.path.join("config", "api_router.py"))
shutil.rmtree(os.path.join("{{cookiecutter.project_slug}}", "users", "api"))
os.remove(os.path.join("{{cookiecutter.project_slug}}", "users", "tests", "test_drf_urls.py"))
os.remove(os.path.join("{{cookiecutter.project_slug}}", "users", "tests", "test_drf_views.py"))
os.remove(os.path.join("{{cookiecutter.project_slug}}", "users", "tests", "test_swagger.py"))
def main():
@ -428,8 +453,6 @@ def main():
if "{{ cookiecutter.use_docker }}".lower() == "y":
remove_utility_files()
if "{{ cookiecutter.cloud_provider }}".lower() != "none":
remove_nginx_docker_files()
else:
remove_docker_files()

View File

@ -1,3 +1,15 @@
"""
NOTE:
the below code is to be maintained Python 2.x-compatible
as the whole Cookiecutter Django project initialization
can potentially be run in Python 2.x environment.
TODO: restrict Cookiecutter Django project initialization
to Python 3.x environments only
"""
from __future__ import print_function
import sys
TERMINATOR = "\x1b[0m"
@ -22,10 +34,36 @@ assert project_slug == project_slug.lower(), "'{}' project slug should be all lo
assert "\\" not in "{{ cookiecutter.author_name }}", "Don't include backslashes in author name."
if "{{ cookiecutter.use_docker }}".lower() == "n":
python_major_version = sys.version_info[0]
if python_major_version == 2:
print(
WARNING + "You're running cookiecutter under Python 2, but the generated "
"project requires Python 3.11+. Do you want to proceed (y/n)? " + TERMINATOR
)
yes_options, no_options = frozenset(["y"]), frozenset(["n"])
while True:
choice = raw_input().lower() # noqa: F821
if choice in yes_options:
break
elif choice in no_options:
print(INFO + "Generation process stopped as requested." + TERMINATOR)
sys.exit(1)
else:
print(
HINT
+ "Please respond with {} or {}: ".format(
", ".join(["'{}'".format(o) for o in yes_options if not o == ""]),
", ".join(["'{}'".format(o) for o in no_options if not o == ""]),
)
+ TERMINATOR
)
if "{{ cookiecutter.use_whitenoise }}".lower() == "n" and "{{ cookiecutter.cloud_provider }}" == "None":
print("You should either use Whitenoise or select a Cloud Provider to serve static files")
print("You should either use Whitenoise or select a " "Cloud Provider to serve static files")
sys.exit(1)
if "{{ cookiecutter.mail_service }}" == "Amazon SES" and "{{ cookiecutter.cloud_provider }}" != "AWS":
print("You should either use AWS or select a different Mail Service for sending emails.")
print("You should either use AWS or select a different " "Mail Service for sending emails.")
sys.exit(1)

View File

@ -1,99 +1,35 @@
[project]
name = "cookiecutter-django"
version = "2025.04.08"
description = "A Cookiecutter template for creating production-ready Django projects quickly."
readme = "README.md"
keywords = [
"cookiecutter",
"django",
"project template",
"scaffolding",
"skeleton",
]
license = { text = "BSD" }
authors = [
{ name = "Daniel Roy Greenfeld", email = "pydanny@gmail.com" },
]
requires-python = ">=3.12,<3.13"
classifiers = [
"Development Status :: 4 - Beta",
"Environment :: Console",
"Framework :: Django :: 5.0",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Programming Language :: Python",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: Implementation :: CPython",
"Topic :: Software Development",
]
dependencies = [
"binaryornot==0.4.4",
"cookiecutter==2.6",
"django-upgrade==1.22.2",
"djlint==1.36.4",
"gitpython==3.1.43",
"jinja2==3.1.5",
"pre-commit==4.1.0",
"pygithub==2.5",
"pytest==8.3.4",
"pytest-cookies==0.7",
"pytest-instafail==0.5",
"pytest-xdist==3.6.1",
"pyyaml==6.0.2",
"requests==2.32.3",
"ruff==0.11.4",
"sh==2.1; sys_platform!='win23'",
"tox==4.23.2",
"tox-uv>=1.17",
]
urls = { Repository = "https://github.com/cookiecutter/cookiecutter-django" }
[dependency-groups]
docs = [
"myst-parser>=4",
"sphinx>=8.0.2",
"sphinx-autobuild>=2024.10.3",
"sphinx-rtd-theme>=3",
# ==== pytest ====
[tool.pytest.ini_options]
addopts = "-v --tb=short"
norecursedirs = [
".tox",
".git",
"*/migrations/*",
"*/static/*",
"docs",
"venv",
"*/{{cookiecutter.project_slug}}/*",
]
# ==== black ====
[tool.black]
line-length = 119
target-version = [
'py312',
]
target-version = ['py311']
# ==== isort ====
[tool.isort]
profile = "black"
line_length = 119
known_first_party = [
"tests",
"scripts",
"hooks",
"tests",
"scripts",
"hooks",
]
[tool.pyproject-fmt]
keep_full_version = true
# ==== pytest ====
[tool.pytest.ini_options]
addopts = "-v --tb=short"
norecursedirs = [
".tox",
".git",
"*/migrations/*",
"*/static/*",
"docs",
"venv",
"*/{{cookiecutter.project_slug}}/*",
]
# ==== djLint ====
[tool.djlint]
blank_line_after_tag = "load,extends"
close_void_tags = true

26
requirements.txt Normal file
View File

@ -0,0 +1,26 @@
cookiecutter==2.5.0
sh==2.0.6; sys_platform != "win32"
binaryornot==0.4.4
# Code quality
# ------------------------------------------------------------------------------
ruff==0.2.1
django-upgrade==1.16.0
djlint==1.34.1
pre-commit==3.6.1
# Testing
# ------------------------------------------------------------------------------
tox==4.12.1
pytest==8.0.0
pytest-xdist==3.5.0
pytest-cookies==0.7.0
pytest-instafail==0.5.0
pyyaml==6.0.1
# Scripting
# ------------------------------------------------------------------------------
PyGithub==2.2.0
gitpython==3.1.41
jinja2==3.1.3
requests==2.31.0

View File

@ -12,6 +12,7 @@ from __future__ import annotations
import os
import re
import sys
from collections.abc import Iterable
from pathlib import Path
from typing import TYPE_CHECKING, Any, NamedTuple
@ -19,8 +20,6 @@ import requests
from github import Github
if TYPE_CHECKING:
from collections.abc import Iterable
from github.Issue import Issue
CURRENT_FILE = Path(__file__)
@ -84,7 +83,7 @@ def get_name_and_version(requirements_line: str) -> tuple[str, ...]:
def get_all_latest_django_versions(
django_max_version: tuple[DjVersion] | None = None,
django_max_version: tuple[DjVersion] = None,
) -> tuple[DjVersion, list[DjVersion]]:
"""
Grabs all Django versions that are worthy of a GitHub issue.
@ -222,7 +221,8 @@ class GitHubManager:
if supported_dj_versions:
if any(v >= needed_dj_version for v in supported_dj_versions):
return package_info["info"]["version"], ""
return "", ""
else:
return "", ""
# Django classifier DNE; assume it isn't a Django lib
# Great exceptions include pylint-django, where we need to do this manually...

View File

@ -1,69 +0,0 @@
from __future__ import annotations
import json
from pathlib import Path
ROOT = Path(__file__).parent.parent
TEMPLATED_ROOT = ROOT / "{{cookiecutter.project_slug}}"
DOCKERFILE = TEMPLATED_ROOT / "compose" / "local" / "node" / "Dockerfile"
PROD_DOCKERFILE = TEMPLATED_ROOT / "compose" / "production" / "django" / "Dockerfile"
PACKAGE_JSON = TEMPLATED_ROOT / "package.json"
CI_YML = ROOT / ".github" / "workflows" / "ci.yml"
def main() -> None:
new_version = get_version_from_dockerfile()
old_version = get_version_from_package_json()
if old_version != new_version:
update_package_json_version(old_version, new_version)
update_ci_node_version(old_version, new_version)
update_production_node_version(old_version, new_version)
def get_version_from_dockerfile() -> str:
# Extract version out of base image name:
# FROM docker.io/node:22.13-bookworm-slim
# -> 22.13
with DOCKERFILE.open("r") as f:
for line in f:
if "FROM docker.io/node:" in line:
_, _, docker_tag = line.partition(":")
version_str, _, _ = docker_tag.partition("-")
return version_str
raise RuntimeError("Could not find version in Dockerfile")
def get_version_from_package_json() -> str:
package_json = json.loads(PACKAGE_JSON.read_text())
return package_json["engines"]["node"]
def update_package_json_version(old_version: str, new_version: str) -> None:
package_json_text = PACKAGE_JSON.read_text()
package_json_text = package_json_text.replace(
f'"node": "{old_version}"',
f'"node": "{new_version}"',
)
PACKAGE_JSON.write_text(package_json_text)
def update_ci_node_version(old_version: str, new_version: str) -> None:
yml_content = CI_YML.read_text()
yml_content = yml_content.replace(
f'node-version: "{old_version}"',
f'node-version: "{new_version}"',
)
CI_YML.write_text(yml_content)
def update_production_node_version(old_version: str, new_version: str) -> None:
dockerfile_content = PROD_DOCKERFILE.read_text()
dockerfile_content = dockerfile_content.replace(
f"FROM docker.io/node:{old_version}",
f"FROM docker.io/node:{new_version}",
)
PROD_DOCKERFILE.write_text(dockerfile_content)
if __name__ == "__main__":
main()

View File

@ -1,56 +0,0 @@
from __future__ import annotations
import subprocess
import tomllib
from pathlib import Path
ROOT = Path(__file__).parent.parent
TEMPLATED_ROOT = ROOT / "{{cookiecutter.project_slug}}"
REQUIREMENTS_LOCAL_TXT = TEMPLATED_ROOT / "requirements" / "local.txt"
PRE_COMMIT_CONFIG = TEMPLATED_ROOT / ".pre-commit-config.yaml"
PYPROJECT_TOML = ROOT / "pyproject.toml"
def main() -> None:
new_version = get_requirements_txt_version()
old_version = get_pyproject_toml_version()
if old_version == new_version:
return
update_ruff_version(old_version, new_version)
subprocess.run(["uv", "lock", "--no-upgrade"], cwd=ROOT)
def get_requirements_txt_version() -> str:
content = REQUIREMENTS_LOCAL_TXT.read_text()
for line in content.split("\n"):
if line.startswith("ruff"):
return line.split(" ")[0].split("==")[1]
raise RuntimeError("Could not find ruff version in requirements/local.txt")
def get_pyproject_toml_version() -> str:
data = tomllib.loads(PYPROJECT_TOML.read_text())
for dependency in data["project"]["dependencies"]:
if dependency.startswith("ruff=="):
return dependency.split("==")[1]
raise RuntimeError("Could not find ruff version in pyproject.toml")
def update_ruff_version(old_version: str, new_version: str) -> None:
# Update pyproject.toml
new_content = PYPROJECT_TOML.read_text().replace(
f"ruff=={old_version}",
f"ruff=={new_version}",
)
PYPROJECT_TOML.write_text(new_content)
# Update pre-commit config
new_content = PRE_COMMIT_CONFIG.read_text().replace(
f"repo: https://github.com/astral-sh/ruff-pre-commit\n rev: v{old_version}",
f"repo: https://github.com/astral-sh/ruff-pre-commit\n rev: v{new_version}",
)
PRE_COMMIT_CONFIG.write_text(new_content)
if __name__ == "__main__":
main()

View File

@ -1,7 +1,6 @@
import datetime as dt
import os
import re
import subprocess
from collections.abc import Iterable
from pathlib import Path
@ -48,16 +47,12 @@ def main() -> None:
print(f"Wrote {changelog_path}")
# Update version
setup_py_path = ROOT / "pyproject.toml"
setup_py_path = ROOT / "setup.py"
update_version(setup_py_path, release)
print(f"Updated version in {setup_py_path}")
# Run uv lock
uv_lock_path = ROOT / "uv.lock"
subprocess.run(["uv", "lock", "--no-upgrade"], cwd=ROOT)
# Commit changes, create tag and push
update_git_repo([changelog_path, setup_py_path, uv_lock_path], release)
update_git_repo([changelog_path, setup_py_path], release)
# Create GitHub release
github_release = repo.create_git_release(
@ -129,7 +124,7 @@ def write_changelog(file_path: Path, release: str, content: str) -> None:
def update_version(file_path: Path, release: str) -> None:
"""Update template version in pyproject.toml."""
"""Update template version in setup.py."""
old_content = file_path.read_text()
updated_content = re.sub(
r'\nversion = "\d+\.\d+\.\d+"\n',

View File

@ -40,8 +40,8 @@ def iter_recent_authors():
"""
Fetch users who opened recently merged pull requests.
Use GitHub API to fetch recent authors rather than
git CLI to work with GitHub usernames.
Use Github API to fetch recent authors rather than
git CLI to work with Github usernames.
"""
repo = Github(login_or_token=GITHUB_TOKEN, per_page=5).get_repo(GITHUB_REPO)
recent_pulls = repo.get_pulls(state="closed", sort="updated", direction="desc").get_page(0)

41
setup.py Normal file
View File

@ -0,0 +1,41 @@
#!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
# We use calendar versioning
version = "2024.02.13"
with open("README.md") as readme_file:
long_description = readme_file.read()
setup(
name="cookiecutter-django",
version=version,
description=("A Cookiecutter template for creating production-ready " "Django projects quickly."),
long_description=long_description,
author="Daniel Roy Greenfeld",
author_email="pydanny@gmail.com",
url="https://github.com/cookiecutter/cookiecutter-django",
packages=[],
license="BSD",
zip_safe=False,
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"Framework :: Django :: 4.2",
"Intended Audience :: Developers",
"Natural Language :: English",
"License :: OSI Approved :: BSD License",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: Implementation :: CPython",
"Topic :: Software Development",
],
keywords=(
"cookiecutter, Python, projects, project templates, django, "
"skeleton, scaffolding, project directory, setup.py"
),
)

View File

@ -11,7 +11,7 @@ mkdir -p .cache/bare
cd .cache/bare
# create the project using the default settings in cookiecutter.json
uv run cookiecutter ../../ --no-input --overwrite-if-exists use_docker=n "$@"
cookiecutter ../../ --no-input --overwrite-if-exists use_docker=n "$@"
cd my_awesome_project
# Install OS deps

View File

@ -2,8 +2,6 @@ import glob
import os
import re
import sys
from collections.abc import Iterable
from pathlib import Path
import pytest
@ -59,10 +57,12 @@ SUPPORTED_COMBINATIONS = [
{"editor": "VS Code"},
{"use_docker": "y"},
{"use_docker": "n"},
{"postgresql_version": "16"},
{"postgresql_version": "15"},
{"postgresql_version": "14"},
{"postgresql_version": "13"},
{"postgresql_version": "12"},
{"postgresql_version": "11"},
{"postgresql_version": "10"},
{"cloud_provider": "AWS", "use_whitenoise": "y"},
{"cloud_provider": "AWS", "use_whitenoise": "n"},
{"cloud_provider": "GCP", "use_whitenoise": "y"},
@ -74,7 +74,7 @@ SUPPORTED_COMBINATIONS = [
{"cloud_provider": "None", "use_whitenoise": "y", "mail_service": "Mandrill"},
{"cloud_provider": "None", "use_whitenoise": "y", "mail_service": "Postmark"},
{"cloud_provider": "None", "use_whitenoise": "y", "mail_service": "Sendgrid"},
{"cloud_provider": "None", "use_whitenoise": "y", "mail_service": "Brevo"},
{"cloud_provider": "None", "use_whitenoise": "y", "mail_service": "SendinBlue"},
{"cloud_provider": "None", "use_whitenoise": "y", "mail_service": "SparkPost"},
{"cloud_provider": "None", "use_whitenoise": "y", "mail_service": "Other SMTP"},
# Note: cloud_provider=None AND use_whitenoise=n is not supported
@ -84,7 +84,7 @@ SUPPORTED_COMBINATIONS = [
{"cloud_provider": "AWS", "mail_service": "Mandrill"},
{"cloud_provider": "AWS", "mail_service": "Postmark"},
{"cloud_provider": "AWS", "mail_service": "Sendgrid"},
{"cloud_provider": "AWS", "mail_service": "Brevo"},
{"cloud_provider": "AWS", "mail_service": "SendinBlue"},
{"cloud_provider": "AWS", "mail_service": "SparkPost"},
{"cloud_provider": "AWS", "mail_service": "Other SMTP"},
{"cloud_provider": "GCP", "mail_service": "Mailgun"},
@ -92,7 +92,7 @@ SUPPORTED_COMBINATIONS = [
{"cloud_provider": "GCP", "mail_service": "Mandrill"},
{"cloud_provider": "GCP", "mail_service": "Postmark"},
{"cloud_provider": "GCP", "mail_service": "Sendgrid"},
{"cloud_provider": "GCP", "mail_service": "Brevo"},
{"cloud_provider": "GCP", "mail_service": "SendinBlue"},
{"cloud_provider": "GCP", "mail_service": "SparkPost"},
{"cloud_provider": "GCP", "mail_service": "Other SMTP"},
{"cloud_provider": "Azure", "mail_service": "Mailgun"},
@ -100,7 +100,7 @@ SUPPORTED_COMBINATIONS = [
{"cloud_provider": "Azure", "mail_service": "Mandrill"},
{"cloud_provider": "Azure", "mail_service": "Postmark"},
{"cloud_provider": "Azure", "mail_service": "Sendgrid"},
{"cloud_provider": "Azure", "mail_service": "Brevo"},
{"cloud_provider": "Azure", "mail_service": "SendinBlue"},
{"cloud_provider": "Azure", "mail_service": "SparkPost"},
{"cloud_provider": "Azure", "mail_service": "Other SMTP"},
# Note: cloud_providers GCP, Azure, and None
@ -147,19 +147,19 @@ def _fixture_id(ctx):
return "-".join(f"{key}:{value}" for key, value in ctx.items())
def build_files_list(base_path: Path):
def build_files_list(base_dir):
"""Build a list containing absolute paths to the generated files."""
return [dirpath / file_path for dirpath, subdirs, files in base_path.walk() for file_path in files]
return [os.path.join(dirpath, file_path) for dirpath, subdirs, files in os.walk(base_dir) for file_path in files]
def check_paths(paths: Iterable[Path]):
def check_paths(paths):
"""Method to check all paths have correct substitutions."""
# Assert that no match is found in any of the files
for path in paths:
if is_binary(str(path)):
if is_binary(path):
continue
for line in path.open():
for line in open(path):
match = RE_OBJ.search(line)
assert match is None, f"cookiecutter variable not replaced in {path}"
@ -174,7 +174,7 @@ def test_project_generation(cookies, context, context_override):
assert result.project_path.name == context["project_slug"]
assert result.project_path.is_dir()
paths = build_files_list(result.project_path)
paths = build_files_list(str(result.project_path))
assert paths
check_paths(paths)
@ -231,7 +231,7 @@ def test_django_upgrade_passes(cookies, context_override):
try:
sh.django_upgrade(
"--target-version",
"5.0",
"4.2",
*python_files,
_cwd=str(result.project_path),
)
@ -248,13 +248,7 @@ def test_djlint_lint_passes(cookies, context_override):
# TODO: remove T002 when fixed https://github.com/Riverside-Healthcare/djLint/issues/687
ignored_rules = "H006,H030,H031,T002"
try:
sh.djlint(
"--lint",
"--ignore",
f"{autofixable_rules},{ignored_rules}",
".",
_cwd=str(result.project_path),
)
sh.djlint("--lint", "--ignore", f"{autofixable_rules},{ignored_rules}", ".", _cwd=str(result.project_path))
except sh.ErrorReturnCode as e:
pytest.fail(e.stdout.decode())
@ -272,10 +266,10 @@ def test_djlint_check_passes(cookies, context_override):
@pytest.mark.parametrize(
("use_docker", "expected_test_script"),
["use_docker", "expected_test_script"],
[
("n", "pytest"),
("y", "docker compose -f docker-compose.local.yml run django pytest"),
("y", "docker compose -f local.yml run django pytest"),
],
)
def test_travis_invokes_pytest(cookies, context, use_docker, expected_test_script):
@ -287,7 +281,7 @@ def test_travis_invokes_pytest(cookies, context, use_docker, expected_test_scrip
assert result.project_path.name == context["project_slug"]
assert result.project_path.is_dir()
with (result.project_path / ".travis.yml").open() as travis_yml:
with open(f"{result.project_path}/.travis.yml") as travis_yml:
try:
yml = yaml.safe_load(travis_yml)["jobs"]["include"]
assert yml[0]["script"] == ["ruff check ."]
@ -297,10 +291,10 @@ def test_travis_invokes_pytest(cookies, context, use_docker, expected_test_scrip
@pytest.mark.parametrize(
("use_docker", "expected_test_script"),
["use_docker", "expected_test_script"],
[
("n", "pytest"),
("y", "docker compose -f docker-compose.local.yml run django pytest"),
("y", "docker compose -f local.yml run django pytest"),
],
)
def test_gitlab_invokes_precommit_and_pytest(cookies, context, use_docker, expected_test_script):
@ -312,11 +306,11 @@ def test_gitlab_invokes_precommit_and_pytest(cookies, context, use_docker, expec
assert result.project_path.name == context["project_slug"]
assert result.project_path.is_dir()
with (result.project_path / ".gitlab-ci.yml").open() as gitlab_yml:
with open(f"{result.project_path}/.gitlab-ci.yml") as gitlab_yml:
try:
gitlab_config = yaml.safe_load(gitlab_yml)
assert gitlab_config["precommit"]["script"] == [
"pre-commit run --show-diff-on-failure --color=always --all-files",
"pre-commit run --show-diff-on-failure --color=always --all-files"
]
assert gitlab_config["pytest"]["script"] == [expected_test_script]
except yaml.YAMLError as e:
@ -324,10 +318,10 @@ def test_gitlab_invokes_precommit_and_pytest(cookies, context, use_docker, expec
@pytest.mark.parametrize(
("use_docker", "expected_test_script"),
["use_docker", "expected_test_script"],
[
("n", "pytest"),
("y", "docker compose -f docker-compose.local.yml run django pytest"),
("y", "docker compose -f local.yml run django pytest"),
],
)
def test_github_invokes_linter_and_pytest(cookies, context, use_docker, expected_test_script):
@ -339,7 +333,7 @@ def test_github_invokes_linter_and_pytest(cookies, context, use_docker, expected
assert result.project_path.name == context["project_slug"]
assert result.project_path.is_dir()
with (result.project_path / ".github" / "workflows" / "ci.yml").open() as github_yml:
with open(f"{result.project_path}/.github/workflows/ci.yml") as github_yml:
try:
github_config = yaml.safe_load(github_yml)
linter_present = False
@ -379,7 +373,7 @@ def test_error_if_incompatible(cookies, context, invalid_context):
@pytest.mark.parametrize(
("editor", "pycharm_docs_exist"),
["editor", "pycharm_docs_exist"],
[
("None", False),
("PyCharm", True),
@ -390,9 +384,9 @@ def test_pycharm_docs_removed(cookies, context, editor, pycharm_docs_exist):
context.update({"editor": editor})
result = cookies.bake(extra_context=context)
index_rst = result.project_path / "docs" / "index.rst"
has_pycharm_docs = "pycharm/configuration" in index_rst.read_text()
assert has_pycharm_docs is pycharm_docs_exist
with open(f"{result.project_path}/docs/index.rst") as f:
has_pycharm_docs = "pycharm/configuration" in f.read()
assert has_pycharm_docs is pycharm_docs_exist
def test_trim_domain_email(cookies, context):
@ -402,7 +396,7 @@ def test_trim_domain_email(cookies, context):
"use_docker": "y",
"domain_name": " example.com ",
"email": " me@example.com ",
},
}
)
result = cookies.bake(extra_context=context)

View File

@ -11,28 +11,29 @@ mkdir -p .cache/docker
cd .cache/docker
# create the project using the default settings in cookiecutter.json
uv run cookiecutter ../../ --no-input --overwrite-if-exists use_docker=y "$@"
cookiecutter ../../ --no-input --overwrite-if-exists use_docker=y "$@"
cd my_awesome_project
# make sure all images build
docker compose -f docker-compose.local.yml build
docker compose -f local.yml build
# run the project's type checks
docker compose -f docker-compose.local.yml run --rm django mypy my_awesome_project
docker compose -f local.yml run django mypy my_awesome_project
# run the project's tests
docker compose -f docker-compose.local.yml run --rm django pytest
docker compose -f local.yml run django pytest
# return non-zero status code if there are migrations that have not been created
docker compose -f docker-compose.local.yml run --rm django python manage.py makemigrations --check || { echo "ERROR: there were changes in the models, but migration listed above have not been created and are not saved in version control"; exit 1; }
docker compose -f local.yml run django python manage.py makemigrations --dry-run --check || { echo "ERROR: there were changes in the models, but migration listed above have not been created and are not saved in version control"; exit 1; }
# Test support for translations
docker compose -f docker-compose.local.yml run --rm django python manage.py makemessages --all
docker compose -f local.yml run django python manage.py makemessages --all
# Make sure the check doesn't raise any warnings
docker compose -f docker-compose.local.yml run --rm \
docker compose -f local.yml run \
-e DJANGO_SECRET_KEY="$(openssl rand -base64 64)" \
-e REDIS_URL=redis://redis:6379/0 \
-e CELERY_BROKER_URL=redis://redis:6379/0 \
-e DJANGO_AWS_ACCESS_KEY_ID=x \
-e DJANGO_AWS_SECRET_ACCESS_KEY=x \
-e DJANGO_AWS_STORAGE_BUCKET_NAME=x \
@ -42,10 +43,10 @@ docker compose -f docker-compose.local.yml run --rm \
django python manage.py check --settings=config.settings.production --deploy --database default --fail-level WARNING
# Generate the HTML for the documentation
docker compose -f docker-compose.docs.yml run --rm docs make html
docker compose -f local.yml run docs make html
# Run npm build script if package.json is present
if [ -f "package.json" ]
then
docker compose -f docker-compose.local.yml run --rm node npm run build
docker compose -f local.yml run node npm run build
fi

View File

@ -8,7 +8,7 @@ import pytest
from hooks.post_gen_project import append_to_gitignore_file
@pytest.fixture
@pytest.fixture()
def working_directory(tmp_path):
prev_cwd = Path.cwd()
os.chdir(tmp_path)

View File

@ -1,11 +1,12 @@
[tox]
skipsdist = true
envlist = py312,black-template
envlist = py311,black-template
[testenv]
deps = -rrequirements.txt
passenv = AUTOFIXABLE_STYLES
commands = pytest -n auto {posargs:./tests}
[testenv:black-template]
deps = black
commands = black --check hooks tests docs scripts
commands = black --check hooks tests setup.py docs scripts

1240
uv.lock

File diff suppressed because it is too large Load Diff

View File

@ -2,7 +2,7 @@
{
"name": "{{cookiecutter.project_slug}}_dev",
"dockerComposeFile": [
"../docker-compose.local.yml"
"../local.yml"
],
"init": true,
"mounts": [
@ -35,7 +35,7 @@
"analysis.typeCheckingMode": "basic",
"defaultInterpreterPath": "/usr/local/bin/python",
"editor.codeActionsOnSave": {
"source.organizeImports": "always"
"source.organizeImports": true
},
"editor.defaultFormatter": "charliermarsh.ruff",
"languageServer": "Pylance",
@ -54,7 +54,8 @@
// python
"ms-python.python",
"ms-python.vscode-pylance",
"charliermarsh.ruff",
"ms-python.isort",
"ms-python.black-formatter",
// django
"batisteo.vscode-django"
]

View File

@ -7,13 +7,13 @@ environment:
POSTGRES_DB: 'test_{{ cookiecutter.project_slug }}'
POSTGRES_HOST_AUTH_METHOD: trust
{%- if cookiecutter.use_celery == 'y' %}
REDIS_URL: 'redis://redis:6379/0'
CELERY_BROKER_URL: 'redis://redis:6379/0'
{%- endif %}
steps:
- name: lint
pull: if-not-exists
image: python:3.12
image: python:3.11
environment:
PRE_COMMIT_HOME: ${CI_PROJECT_DIR}/.cache/pre-commit
volumes:
@ -27,17 +27,16 @@ steps:
- name: test
pull: if-not-exists
{%- if cookiecutter.use_docker == 'y' %}
image: docker:25.0
image: docker/compose:1.29.2
environment:
DATABASE_URL: pgsql://$POSTGRES_USER:$POSTGRES_PASSWORD@postgres/$POSTGRES_DB
commands:
- docker-compose -f docker-compose.local.yml build
- docker-compose -f docker-compose.docs.yml build
- docker-compose -f docker-compose.local.yml run --rm django python manage.py migrate
- docker-compose -f docker-compose.local.yml up -d
- docker-compose -f docker-compose.local.yml run django pytest
- docker-compose -f local.yml build
- docker-compose -f local.yml run --rm django python manage.py migrate
- docker-compose -f local.yml up -d
- docker-compose -f local.yml run django pytest
{%- else %}
image: python:3.12
image: python:3.11
commands:
- pip install -r requirements/local.txt
- pytest

View File

@ -12,7 +12,7 @@ trim_trailing_whitespace = true
indent_style = space
indent_size = 4
[*.{html,css,scss,json,yml,xml,toml}]
[*.{html,css,scss,json,yml,xml}]
indent_style = space
indent_size = 2

View File

@ -28,8 +28,8 @@ POSTMARK_SERVER_TOKEN=
SENDGRID_API_KEY=
SENDGRID_GENERATE_MESSAGE_ID=True
SENDGRID_MERGE_FIELD_FORMAT=None
{% elif cookiecutter.mail_service == 'Brevo' %}
BREVO_API_KEY=
{% elif cookiecutter.mail_service == 'SendinBlue' %}
SENDINBLUE_API_KEY=
{% elif cookiecutter.mail_service == 'SparkPost' %}
SPARKPOST_API_KEY=
{% endif %}

View File

@ -1,5 +1,5 @@
# Config for Dependabot updates. See Documentation here:
# https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
@ -9,20 +9,16 @@ updates:
# Every weekday
schedule:
interval: 'daily'
groups:
github-actions:
patterns:
- '*'
{%- if cookiecutter.use_docker == 'y' %}
# Enable version updates for Docker
# We need to specify each Dockerfile in a separate entry because Dependabot doesn't
# support wildcards or recursively checking subdirectories. Check this issue for updates:
# https://github.com/dependabot/dependabot-core/issues/2178
- package-ecosystem: 'docker'
# Look for a `Dockerfile` in the `compose/local/django` directory
directories:
- 'compose/local/django/'
- 'compose/local/docs/'
- 'compose/production/django/'
directory: 'compose/local/django/'
# Every weekday
schedule:
interval: 'daily'
@ -32,22 +28,57 @@ updates:
update-types:
- 'version-update:semver-major'
- 'version-update:semver-minor'
groups:
docker-python:
patterns:
- '*'
- package-ecosystem: 'docker'
# Look for a `Dockerfile` in the listed directories
directories:
- 'compose/local/node/'
- 'compose/production/aws/'
- 'compose/production/postgres/'
- 'compose/production/traefik/'
{%- if cookiecutter.cloud_provider == 'None' %}
- 'compose/production/nginx/'
{%- endif %}
# Look for a `Dockerfile` in the `compose/local/docs` directory
directory: 'compose/local/docs/'
# Every weekday
schedule:
interval: 'daily'
# Ignore minor version updates (3.10 -> 3.11) but update patch versions
ignore:
- dependency-name: '*'
update-types:
- 'version-update:semver-major'
- 'version-update:semver-minor'
- package-ecosystem: 'docker'
# Look for a `Dockerfile` in the `compose/local/node` directory
directory: 'compose/local/node/'
# Every weekday
schedule:
interval: 'daily'
- package-ecosystem: 'docker'
# Look for a `Dockerfile` in the `compose/production/aws` directory
directory: 'compose/production/aws/'
# Every weekday
schedule:
interval: 'daily'
- package-ecosystem: 'docker'
# Look for a `Dockerfile` in the `compose/production/django` directory
directory: 'compose/production/django/'
# Every weekday
schedule:
interval: 'daily'
# Ignore minor version updates (3.10 -> 3.11) but update patch versions
ignore:
- dependency-name: '*'
update-types:
- 'version-update:semver-major'
- 'version-update:semver-minor'
- package-ecosystem: 'docker'
# Look for a `Dockerfile` in the `compose/production/postgres` directory
directory: 'compose/production/postgres/'
# Every weekday
schedule:
interval: 'daily'
- package-ecosystem: 'docker'
# Look for a `Dockerfile` in the `compose/production/traefik` directory
directory: 'compose/production/traefik/'
# Every weekday
schedule:
interval: 'daily'
@ -57,16 +88,11 @@ updates:
# Enable version updates for Python/Pip - Production
- package-ecosystem: 'pip'
# Look for a `requirements.txt` in the `root` directory
# also 'setup.cfg', '.python-version' and 'requirements/*.txt'
# also 'setup.cfg', 'runtime.txt' and 'requirements/*.txt'
directory: '/'
# Every weekday
schedule:
interval: 'daily'
groups:
python:
update-types:
- 'minor'
- 'patch'
{%- if cookiecutter.frontend_pipeline == 'Gulp' %}
@ -77,10 +103,5 @@ updates:
# Every weekday
schedule:
interval: 'daily'
groups:
javascript:
update-types:
- 'minor'
- 'patch'
{%- endif %}

View File

@ -26,17 +26,17 @@ jobs:
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
uses: actions/setup-python@v4
with:
python-version-file: '.python-version'
python-version: '3.11'
{%- if cookiecutter.open_source_license != 'Not open source' %}
# Consider using pre-commit.ci for open source project
{%- endif %}
- name: Run pre-commit
uses: pre-commit/action@v3.0.1
uses: pre-commit/action@v3.0.0
# With no caching at all the entire ci process takes 3m to complete!
# With no caching at all the entire ci process takes 4m 30s to complete!
pytest:
runs-on: ubuntu-latest
{%- if cookiecutter.use_docker == 'n' %}
@ -57,7 +57,7 @@ jobs:
env:
{%- if cookiecutter.use_celery == 'y' %}
REDIS_URL: 'redis://localhost:6379/0'
CELERY_BROKER_URL: 'redis://localhost:6379/0'
{%- endif %}
# postgres://user:password@host:port/database
DATABASE_URL: 'postgres://postgres:postgres@localhost:5432/postgres'
@ -68,49 +68,23 @@ jobs:
uses: actions/checkout@v4
{%- if cookiecutter.use_docker == 'y' %}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build and cache local backend
uses: docker/bake-action@v6
with:
push: false
load: true
files: docker-compose.local.yml
targets: django
set: |
django.cache-from=type=gha,scope=django-cached-tests
django.cache-to=type=gha,scope=django-cached-tests,mode=max
postgres.cache-from=type=gha,scope=postgres-cached-tests
postgres.cache-to=type=gha,scope=postgres-cached-tests,mode=max
- name: Build and cache docs
uses: docker/bake-action@v6
with:
push: false
load: true
files: docker-compose.docs.yml
set: |
docs.cache-from=type=gha,scope=cached-docs
docs.cache-to=type=gha,scope=cached-docs,mode=max
- name: Check DB Migrations
run: docker compose -f docker-compose.local.yml run --rm django python manage.py makemigrations --check
- name: Build the Stack
run: docker compose -f local.yml build
- name: Run DB Migrations
run: docker compose -f docker-compose.local.yml run --rm django python manage.py migrate
run: docker compose -f local.yml run --rm django python manage.py migrate
- name: Run Django Tests
run: docker compose -f docker-compose.local.yml run django pytest
run: docker compose -f local.yml run django pytest
- name: Tear down the Stack
run: docker compose -f docker-compose.local.yml down
run: docker compose -f local.yml down
{%- else %}
- name: Set up Python
uses: actions/setup-python@v5
uses: actions/setup-python@v4
with:
python-version-file: '.python-version'
python-version: '3.11'
cache: pip
cache-dependency-path: |
requirements/base.txt
@ -121,12 +95,6 @@ jobs:
python -m pip install --upgrade pip
pip install -r requirements/local.txt
- name: Check DB Migrations
run: python manage.py makemigrations --check
- name: Run DB Migrations
run: python manage.py migrate
- name: Test with pytest
run: pytest
{%- endif %}

View File

@ -59,6 +59,9 @@ docs/_build/
# PyBuilder
target/
# pyenv
.python-version
{% if cookiecutter.use_celery == 'y' -%}
# celery beat schedule file
celerybeat-schedule

View File

@ -8,12 +8,12 @@ variables:
POSTGRES_DB: 'test_{{ cookiecutter.project_slug }}'
POSTGRES_HOST_AUTH_METHOD: trust
{%- if cookiecutter.use_celery == 'y' %}
REDIS_URL: 'redis://redis:6379/0'
CELERY_BROKER_URL: 'redis://redis:6379/0'
{%- endif %}
precommit:
stage: lint
image: python:3.12
image: python:3.11
variables:
PRE_COMMIT_HOME: ${CI_PROJECT_DIR}/.cache/pre-commit
cache:
@ -27,19 +27,22 @@ precommit:
pytest:
stage: test
{%- if cookiecutter.use_docker == 'y' %}
image: docker:25.0
image: docker/compose:1.29.2
tags:
- docker
services:
- docker:dind
before_script:
- docker compose -f docker-compose.local.yml build
- docker compose -f docker-compose.docs.yml build
- docker compose -f local.yml build
# Ensure celerybeat does not crash due to non-existent tables
- docker compose -f docker-compose.local.yml run --rm django python manage.py migrate
- docker compose -f docker-compose.local.yml up -d
- docker compose -f local.yml run --rm django python manage.py migrate
- docker compose -f local.yml up -d
script:
- docker compose -f docker-compose.local.yml run django pytest
- docker compose -f local.yml run django pytest
{%- else %}
image: python:3.12
image: python:3.11
tags:
- python
services:
- postgres:{{ cookiecutter.postgresql_version }}
variables:

View File

@ -15,7 +15,7 @@
{%- endif %}
</list>
</option>
<option name="sourceFilePath" value="docker-compose.local.yml"/>
<option name="sourceFilePath" value="local.yml"/>
</settings>
</deployment>
<method v="2"/>

View File

@ -8,7 +8,7 @@
<option value="docs"/>
</list>
</option>
<option name="sourceFilePath" value="docker-compose.local.yml"/>
<option name="sourceFilePath" value="local.yml"/>
</settings>
</deployment>
<method v="2"/>

View File

@ -1,13 +1,12 @@
exclude: '^docs/|/migrations/|devcontainer.json'
default_stages: [pre-commit]
minimum_pre_commit_version: "3.2.0"
default_stages: [commit]
default_language_version:
python: python3.12
python: python3.11
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
rev: v4.5.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
@ -29,14 +28,14 @@ repos:
exclude: '{{cookiecutter.project_slug}}/templates/'
- repo: https://github.com/adamchainz/django-upgrade
rev: '1.24.0'
rev: '1.16.0'
hooks:
- id: django-upgrade
args: ['--target-version', '5.0']
args: ['--target-version', '4.2']
# Run the Ruff linter.
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.11.4
rev: v0.2.1
hooks:
# Linter
- id: ruff
@ -45,7 +44,7 @@ repos:
- id: ruff-format
- repo: https://github.com/Riverside-Healthcare/djLint
rev: v1.36.4
rev: v1.34.1
hooks:
- id: djlint-reformat-django
- id: djlint-django

View File

@ -1 +0,0 @@
3.12

View File

@ -8,7 +8,7 @@ version: 2
build:
os: ubuntu-22.04
tools:
python: '3.12'
python: '3.11'
# Build documentation in the docs/ directory with Sphinx
sphinx:

View File

@ -2,7 +2,7 @@ dist: focal
language: python
python:
- "3.12"
- "3.11"
services:
- {% if cookiecutter.use_docker == 'y' %}docker{% else %}postgresql{% endif %}
@ -19,15 +19,14 @@ jobs:
before_script:
- docker compose -v
- docker -v
- docker compose -f docker-compose.local.yml build
- docker compose -f docker-compose.docs.yml build
- docker compose -f local.yml build
# Ensure celerybeat does not crash due to non-existent tables
- docker compose -f docker-compose.local.yml run --rm django python manage.py migrate
- docker compose -f docker-compose.local.yml up -d
- docker compose -f local.yml run --rm django python manage.py migrate
- docker compose -f local.yml up -d
script:
- docker compose -f docker-compose.local.yml run django pytest
- docker compose -f local.yml run django pytest
after_failure:
- docker compose -f docker-compose.local.yml logs
- docker compose -f local.yml logs
{%- else %}
before_install:
- sudo apt-get update -qq
@ -38,7 +37,7 @@ jobs:
- sudo apt-get install -qq libsqlite3-dev libxml2 libxml2-dev libssl-dev libbz2-dev wget curl llvm
language: python
python:
- "3.12"
- "3.11"
install:
- pip install -r requirements/local.txt
script:

View File

@ -1,6 +1,6 @@
release: python manage.py migrate
{%- if cookiecutter.use_async == "y" %}
web: gunicorn config.asgi:application -k uvicorn_worker.UvicornWorker
web: gunicorn config.asgi:application -k uvicorn.workers.UvicornWorker
{%- else %}
web: gunicorn config.wsgi:application
{%- endif %}

View File

@ -12,7 +12,7 @@ License: {{cookiecutter.open_source_license}}
## Settings
Moved to [settings](https://cookiecutter-django.readthedocs.io/en/latest/1-getting-started/settings.html).
Moved to [settings](http://cookiecutter-django.readthedocs.io/en/latest/settings.html).
## Basic Commands
@ -46,7 +46,7 @@ To run the tests, check your test coverage, and generate an HTML coverage report
### Live reloading and Sass CSS compilation
Moved to [Live reloading and SASS compilation](https://cookiecutter-django.readthedocs.io/en/latest/2-local-development/developing-locally.html#using-webpack-or-gulp).
Moved to [Live reloading and SASS compilation](https://cookiecutter-django.readthedocs.io/en/latest/developing-locally.html#sass-compilation-live-reloading).
{%- if cookiecutter.use_celery == "y" %}
@ -87,7 +87,7 @@ celery -A config.celery_app worker -B -l info
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](https://github.com/axllent/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](https://cookiecutter-django.readthedocs.io/en/latest/2-local-development/developing-locally-docker.html) for more details how to start all containers.
Please check [cookiecutter-django Docker documentation](http://cookiecutter-django.readthedocs.io/en/latest/deployment-with-docker.html) 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 %}
@ -130,14 +130,14 @@ The following details how to deploy this application.
### Heroku
See detailed [cookiecutter-django Heroku documentation](https://cookiecutter-django.readthedocs.io/en/latest/3-deployment/deployment-on-heroku.html).
See detailed [cookiecutter-django Heroku documentation](http://cookiecutter-django.readthedocs.io/en/latest/deployment-on-heroku.html).
{%- endif %}
{%- if cookiecutter.use_docker.lower() == "y" %}
### Docker
See detailed [cookiecutter-django Docker documentation](https://cookiecutter-django.readthedocs.io/en/latest/3-deployment/deployment-with-docker.html).
See detailed [cookiecutter-django Docker documentation](http://cookiecutter-django.readthedocs.io/en/latest/deployment-with-docker.html).
{%- endif %}
{%- if cookiecutter.frontend_pipeline in ['Gulp', 'Webpack'] %}

View File

@ -1,8 +1,8 @@
# define an alias for the specific python version used in this file.
FROM docker.io/python:3.12.9-slim-bookworm AS python
FROM docker.io/python:3.11.8-slim-bookworm as python
# Python build stage
FROM python AS python-build-stage
FROM docker.io/python as python-build-stage
ARG BUILD_ENVIRONMENT=local
@ -10,7 +10,7 @@ ARG BUILD_ENVIRONMENT=local
RUN apt-get update && apt-get install --no-install-recommends -y \
# dependencies for building Python packages
build-essential \
# psycopg dependencies
# psycopg2 dependencies
libpq-dev
# Requirements are installed here to ensure they will be cached.
@ -22,14 +22,14 @@ RUN pip wheel --wheel-dir /usr/src/app/wheels \
# Python 'run' stage
FROM python AS python-run-stage
FROM docker.io/python as python-run-stage
ARG BUILD_ENVIRONMENT=local
ARG APP_HOME=/app
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
ENV BUILD_ENV=${BUILD_ENVIRONMENT}
ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1
ENV BUILD_ENV ${BUILD_ENVIRONMENT}
WORKDIR ${APP_HOME}
@ -47,9 +47,8 @@ RUN groupadd --gid 1000 dev-user \
# Install required system dependencies
RUN apt-get update && apt-get install --no-install-recommends -y \
# psycopg dependencies
libpq-dev \
wait-for-it \
# psycopg2 dependencies
libpq-dev \
# Translations dependencies
gettext \
# cleaning up unused files

View File

@ -3,14 +3,6 @@
set -o errexit
set -o nounset
until timeout 10 celery -A config.celery_app inspect ping; do
>&2 echo "Celery workers not available"
done
echo 'Starting flower'
exec watchfiles --filter python celery.__main__.main \
--args \
"-A config.celery_app -b \"${REDIS_URL}\" flower --basic_auth=\"${CELERY_FLOWER_USER}:${CELERY_FLOWER_PASSWORD}\""
"-A config.celery_app -b \"${CELERY_BROKER_URL}\" flower --basic_auth=\"${CELERY_FLOWER_USER}:${CELERY_FLOWER_PASSWORD}\""

View File

@ -1,16 +1,16 @@
# define an alias for the specific python version used in this file.
FROM docker.io/python:3.12.9-slim-bookworm AS python
FROM docker.io/python:3.11.8-slim-bookworm as python
# Python build stage
FROM python AS python-build-stage
FROM docker.io/python as python-build-stage
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONDONTWRITEBYTECODE 1
RUN apt-get update && apt-get install --no-install-recommends -y \
# dependencies for building Python packages
build-essential \
# psycopg dependencies
# psycopg2 dependencies
libpq-dev \
# cleaning up unused files
&& apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \
@ -26,16 +26,16 @@ RUN pip wheel --no-cache-dir --wheel-dir /usr/src/app/wheels \
# Python 'run' stage
FROM python AS python-run-stage
FROM docker.io/python as python-run-stage
ARG BUILD_ENVIRONMENT
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1
RUN apt-get update && apt-get install --no-install-recommends -y \
# To run the Makefile
make \
# psycopg dependencies
# psycopg2 dependencies
libpq-dev \
# Translations dependencies
gettext \

View File

@ -1,4 +1,4 @@
FROM docker.io/node:22.14-bookworm-slim
FROM docker.io/node:20-bookworm-slim
WORKDIR /app
@ -6,4 +6,4 @@ COPY ./package.json /app
RUN npm install && npm cache clean --force
ENV PATH=./node_modules/.bin/:$PATH
ENV PATH ./node_modules/.bin/:$PATH

View File

@ -1,8 +1,4 @@
FROM docker.io/amazon/aws-cli:2.25.0
# Clear entrypoint from the base image, otherwise it's always calling the aws CLI
ENTRYPOINT []
CMD ["/bin/bash"]
FROM docker.io/garland/aws-cli-docker:1.16.140
COPY ./compose/production/aws/maintenance /usr/local/bin/maintenance
COPY ./compose/production/postgres/maintenance/_sourced /usr/local/bin/maintenance/_sourced

View File

@ -3,7 +3,7 @@
### Download a file from your Amazon S3 bucket to the postgres /backups folder
###
### Usage:
### $ docker compose -f docker-compose.production.yml run --rm awscli <1>
### $ docker compose -f production.yml run --rm awscli <1>
set -o errexit
set -o pipefail

View File

@ -3,7 +3,7 @@
### Upload the /backups folder to Amazon S3
###
### Usage:
### $ docker compose -f docker-compose.production.yml run --rm awscli upload
### $ docker compose -f production.yml run --rm awscli upload
set -o errexit
set -o pipefail

View File

@ -1,5 +1,5 @@
{% if cookiecutter.frontend_pipeline in ['Gulp', 'Webpack'] -%}
FROM docker.io/node:22.14-bookworm-slim AS client-builder
FROM docker.io/node:20-bookworm-slim as client-builder
ARG APP_HOME=/app
WORKDIR ${APP_HOME}
@ -25,10 +25,10 @@ RUN npm run build
{%- endif %}
# define an alias for the specific python version used in this file.
FROM docker.io/python:3.12.9-slim-bookworm AS python
FROM docker.io/python:3.11.8-slim-bookworm as python
# Python build stage
FROM python AS python-build-stage
FROM docker.io/python as python-build-stage
ARG BUILD_ENVIRONMENT=production
@ -36,10 +36,9 @@ ARG BUILD_ENVIRONMENT=production
RUN apt-get update && apt-get install --no-install-recommends -y \
# dependencies for building Python packages
build-essential \
# psycopg dependencies
# psycopg2 dependencies
libpq-dev
# Requirements are installed here to ensure they will be cached.
COPY ./requirements .
@ -49,29 +48,27 @@ RUN pip wheel --wheel-dir /usr/src/app/wheels \
# Python 'run' stage
FROM python AS python-run-stage
FROM docker.io/python as python-run-stage
ARG BUILD_ENVIRONMENT=production
ARG APP_HOME=/app
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
ENV BUILD_ENV=${BUILD_ENVIRONMENT}
ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1
ENV BUILD_ENV ${BUILD_ENVIRONMENT}
WORKDIR ${APP_HOME}
RUN addgroup --system django \
&& adduser --system --ingroup django django
&& adduser --system --ingroup django django
# Install required system dependencies
RUN apt-get update && apt-get install --no-install-recommends -y \
# psycopg dependencies
# psycopg2 dependencies
libpq-dev \
# Translations dependencies
gettext \
# entrypoint
wait-for-it \
# cleaning up unused files
&& apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \
&& rm -rf /var/lib/apt/lists/*
@ -120,11 +117,14 @@ COPY --chown=django:django . ${APP_HOME}
{%- endif %}
# make django owner of the WORKDIR directory as well.
RUN chown -R django:django ${APP_HOME}
RUN chown django:django ${APP_HOME}
USER django
RUN DATABASE_URL="" \
{%- if cookiecutter.use_celery == "y" %}
CELERY_BROKER_URL="" \
{%- endif %}
DJANGO_SETTINGS_MODULE="config.settings.test" \
python manage.py compilemessages

View File

@ -4,16 +4,8 @@ set -o errexit
set -o nounset
until timeout 10 celery -A config.celery_app inspect ping; do
>&2 echo "Celery workers not available"
done
echo 'Starting flower'
exec celery \
-A config.celery_app \
-b "${REDIS_URL}" \
-b "${CELERY_BROKER_URL}" \
flower \
--basic_auth="${CELERY_FLOWER_USER}:${CELERY_FLOWER_PASSWORD}"

View File

@ -4,13 +4,45 @@ set -o errexit
set -o pipefail
set -o nounset
{% if cookiecutter.use_celery == 'y' %}
# N.B. If only .env files supported variable expansion...
export CELERY_BROKER_URL="${REDIS_URL}"
{% endif %}
if [ -z "${POSTGRES_USER}" ]; then
base_postgres_image_default_user='postgres'
export POSTGRES_USER="${base_postgres_image_default_user}"
fi
export DATABASE_URL="postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}"
wait-for-it "${POSTGRES_HOST}:${POSTGRES_PORT}" -t 30
python << END
import sys
import time
import psycopg
suggest_unrecoverable_after = 30
start = time.time()
while True:
try:
psycopg.connect(
dbname="${POSTGRES_DB}",
user="${POSTGRES_USER}",
password="${POSTGRES_PASSWORD}",
host="${POSTGRES_HOST}",
port="${POSTGRES_PORT}",
)
break
except psycopg.OperationalError as error:
sys.stderr.write("Waiting for PostgreSQL to become available...\n")
if time.time() - start > suggest_unrecoverable_after:
sys.stderr.write(" This is taking longer than expected. The following exception may be indicative of an unrecoverable error: '{}'\n".format(error))
time.sleep(1)
END
>&2 echo 'PostgreSQL is available'

View File

@ -28,7 +28,7 @@ if compress_enabled; then
fi
{%- endif %}
{%- if cookiecutter.use_async == 'y' %}
exec /usr/local/bin/gunicorn config.asgi --bind 0.0.0.0:5000 --chdir=/app -k uvicorn_worker.UvicornWorker
exec /usr/local/bin/gunicorn config.asgi --bind 0.0.0.0:5000 --chdir=/app -k uvicorn.workers.UvicornWorker
{%- else %}
exec /usr/local/bin/gunicorn config.wsgi --bind 0.0.0.0:5000 --chdir=/app
{%- endif %}

View File

@ -1,4 +1,4 @@
FROM docker.io/traefik:3.3.5
FROM docker.io/traefik:2.11.0
RUN mkdir -p /etc/traefik/acme \
&& touch /etc/traefik/acme/acme.json \
&& chmod 600 /etc/traefik/acme/acme.json

View File

@ -1,3 +1,4 @@
# ruff: noqa
"""
ASGI config for {{ cookiecutter.project_name }} project.
@ -24,9 +25,12 @@ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
# This application object is used by any ASGI server configured to use this file.
django_application = get_asgi_application()
# Apply ASGI middleware here.
# from helloworld.asgi import HelloWorldApplication
# application = HelloWorldApplication(application)
# Import websocket application here, so apps from django_application are loaded first
from config.websocket import websocket_application # noqa: E402
from config.websocket import websocket_application
async def application(scope, receive, send):

View File

@ -1,7 +1,6 @@
import os
from celery import Celery
from celery.signals import setup_logging
# set the default Django settings module for the 'celery' program.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
@ -14,15 +13,5 @@ app = Celery("{{cookiecutter.project_slug}}")
# should have a `CELERY_` prefix.
app.config_from_object("django.conf:settings", namespace="CELERY")
@setup_logging.connect
def config_loggers(*args, **kwargs):
from logging.config import dictConfig
from django.conf import settings
dictConfig(settings.LOGGING)
# Load task modules from all registered Django app configs.
app.autodiscover_tasks()

View File

@ -1,9 +1,6 @@
# ruff: noqa: ERA001, E501
"""Base settings to build other settings files upon."""
{% if cookiecutter.use_celery == 'y' -%}
import ssl
{%- endif %}
from pathlib import Path
import environ
@ -87,7 +84,6 @@ THIRD_PARTY_APPS = [
"crispy_bootstrap5",
"allauth",
"allauth.account",
"allauth.mfa",
"allauth.socialaccount",
{%- if cookiecutter.use_celery == 'y' %}
"django_celery_beat",
@ -285,9 +281,6 @@ LOGGING = {
"root": {"level": "INFO", "handlers": ["console"]},
}
REDIS_URL = env("REDIS_URL", default="redis://{% if cookiecutter.use_docker == 'y' %}redis{%else%}localhost{% endif %}:6379/0")
REDIS_SSL = REDIS_URL.startswith("rediss://")
{% if cookiecutter.use_celery == 'y' -%}
# Celery
# ------------------------------------------------------------------------------
@ -295,13 +288,9 @@ if USE_TZ:
# https://docs.celeryq.dev/en/stable/userguide/configuration.html#std:setting-timezone
CELERY_TIMEZONE = TIME_ZONE
# https://docs.celeryq.dev/en/stable/userguide/configuration.html#std:setting-broker_url
CELERY_BROKER_URL = REDIS_URL
# https://docs.celeryq.dev/en/stable/userguide/configuration.html#redis-backend-use-ssl
CELERY_BROKER_USE_SSL = {"ssl_cert_reqs": ssl.CERT_NONE} if REDIS_SSL else None
CELERY_BROKER_URL = env("CELERY_BROKER_URL")
# https://docs.celeryq.dev/en/stable/userguide/configuration.html#std:setting-result_backend
CELERY_RESULT_BACKEND = REDIS_URL
# https://docs.celeryq.dev/en/stable/userguide/configuration.html#redis-backend-use-ssl
CELERY_REDIS_BACKEND_USE_SSL = CELERY_BROKER_USE_SSL
CELERY_RESULT_BACKEND = CELERY_BROKER_URL
# https://docs.celeryq.dev/en/stable/userguide/configuration.html#result-extended
CELERY_RESULT_EXTENDED = True
# https://docs.celeryq.dev/en/stable/userguide/configuration.html#result-backend-always-retry
@ -327,20 +316,18 @@ CELERY_BEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler"
CELERY_WORKER_SEND_TASK_EVENTS = True
# https://docs.celeryq.dev/en/stable/userguide/configuration.html#std-setting-task_send_sent_event
CELERY_TASK_SEND_SENT_EVENT = True
# https://docs.celeryq.dev/en/stable/userguide/configuration.html#worker-hijack-root-logger
CELERY_WORKER_HIJACK_ROOT_LOGGER = False
{%- endif %}
# django-allauth
# ------------------------------------------------------------------------------
ACCOUNT_ALLOW_REGISTRATION = env.bool("DJANGO_ACCOUNT_ALLOW_REGISTRATION", True)
# https://docs.allauth.org/en/latest/account/configuration.html
ACCOUNT_LOGIN_METHODS = {"{{cookiecutter.username_type}}"}
ACCOUNT_AUTHENTICATION_METHOD = "{{cookiecutter.username_type}}"
# https://docs.allauth.org/en/latest/account/configuration.html
{%- if cookiecutter.username_type == "username" %}
ACCOUNT_SIGNUP_FIELDS = ["email*", "username*", "password1*", "password2*"]
{%- else %}
ACCOUNT_SIGNUP_FIELDS = ["email*", "password1*", "password2*"]
ACCOUNT_EMAIL_REQUIRED = True
{%- if cookiecutter.username_type == "email" %}
# https://docs.allauth.org/en/latest/account/configuration.html
ACCOUNT_USERNAME_REQUIRED = False
# https://docs.allauth.org/en/latest/account/configuration.html
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
{%- endif %}
@ -384,7 +371,6 @@ SPECTACULAR_SETTINGS = {
"DESCRIPTION": "Documentation of API endpoints of {{ cookiecutter.project_name }}",
"VERSION": "1.0.0",
"SERVE_PERMISSIONS": ["rest_framework.permissions.IsAdminUser"],
"SCHEMA_PATH_PREFIX": "/api/",
}
{%- endif %}
{%- if cookiecutter.frontend_pipeline == 'Webpack' %}

View File

@ -64,12 +64,7 @@ INSTALLED_APPS += ["debug_toolbar"]
MIDDLEWARE += ["debug_toolbar.middleware.DebugToolbarMiddleware"]
# https://django-debug-toolbar.readthedocs.io/en/latest/configuration.html#debug-toolbar-config
DEBUG_TOOLBAR_CONFIG = {
"DISABLE_PANELS": [
"debug_toolbar.panels.redirects.RedirectsPanel",
# Disable profiling panel due to an issue with Python 3.12:
# https://github.com/jazzband/django-debug-toolbar/issues/1875
"debug_toolbar.panels.profiling.ProfilingPanel",
],
"DISABLE_PANELS": ["debug_toolbar.panels.redirects.RedirectsPanel"],
"SHOW_TEMPLATE_CONTEXT": True,
}
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#internal-ips
@ -88,15 +83,6 @@ if env("USE_DOCKER") == "yes":
# The node container isn't started (yet?)
pass
{%- endif %}
{%- if cookiecutter.windows == 'y' %}
# RunServerPlus
# ------------------------------------------------------------------------------
# This is a custom setting for RunServerPlus to fix reloader issue in Windows docker environment
# Werkzeug reloader type [auto, watchdog, or stat]
RUNSERVERPLUS_POLLER_RELOADER_TYPE = 'stat'
# If you have CPU and IO load issues, you can increase this poller interval e.g) 5
RUNSERVERPLUS_POLLER_RELOADER_INTERVAL = 1
{%- endif %}
{%- endif %}
# django-extensions

View File

@ -16,7 +16,6 @@ from sentry_sdk.integrations.redis import RedisIntegration
from .base import * # noqa: F403
from .base import DATABASES
from .base import INSTALLED_APPS
from .base import REDIS_URL
{%- if cookiecutter.use_drf == "y" %}
from .base import SPECTACULAR_SETTINGS
{%- endif %}
@ -38,10 +37,10 @@ DATABASES["default"]["CONN_MAX_AGE"] = env.int("CONN_MAX_AGE", default=60)
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": REDIS_URL,
"LOCATION": env("REDIS_URL"),
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
# Mimicking memcache behavior.
# Mimicing memcache behavior.
# https://github.com/jazzband/django-redis#memcached-exceptions-behavior
"IGNORE_EXCEPTIONS": True,
},
@ -56,12 +55,8 @@ SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True)
# https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-secure
SESSION_COOKIE_SECURE = True
# https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-name
SESSION_COOKIE_NAME = "__Secure-sessionid"
# https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-secure
CSRF_COOKIE_SECURE = True
# https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-name
CSRF_COOKIE_NAME = "__Secure-csrftoken"
# https://docs.djangoproject.com/en/dev/topics/security/#ssl-https
# https://docs.djangoproject.com/en/dev/ref/settings/#secure-hsts-seconds
# TODO: set this to 60 seconds first and then to 518400 once you prove the former works
@ -79,6 +74,12 @@ SECURE_CONTENT_TYPE_NOSNIFF = env.bool(
default=True,
)
{% if cookiecutter.cloud_provider != 'None' -%}
# STORAGES
# ------------------------------------------------------------------------------
# https://django-storages.readthedocs.io/en/latest/#installation
INSTALLED_APPS += ["storages"]
{%- endif -%}
{% if cookiecutter.cloud_provider == 'AWS' %}
# https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html#settings
AWS_ACCESS_KEY_ID = env("DJANGO_AWS_ACCESS_KEY_ID")
@ -117,7 +118,7 @@ AZURE_CONTAINER = env("DJANGO_AZURE_CONTAINER_NAME")
# STATIC & MEDIA
# ------------------------
STORAGES = {
{%- if cookiecutter.use_whitenoise == 'y' and cookiecutter.cloud_provider == 'None' %}
{%- if cookiecutter.use_whitenoise == 'y' %}
"default": {
"BACKEND": "django.core.files.storage.FileSystemStorage",
},
@ -132,11 +133,6 @@ STORAGES = {
"file_overwrite": False,
},
},
{%- if cookiecutter.use_whitenoise == 'y' %}
"staticfiles": {
"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage",
},
{%- else %}
"staticfiles": {
"BACKEND": "storages.backends.s3.S3Storage",
"OPTIONS": {
@ -144,7 +140,6 @@ STORAGES = {
"default_acl": "public-read",
},
},
{%- endif %}
{%- elif cookiecutter.cloud_provider == 'GCP' %}
"default": {
"BACKEND": "storages.backends.gcloud.GoogleCloudStorage",
@ -153,11 +148,6 @@ STORAGES = {
"file_overwrite": False,
},
},
{%- if cookiecutter.use_whitenoise == 'y' %}
"staticfiles": {
"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage",
},
{%- else %}
"staticfiles": {
"BACKEND": "storages.backends.gcloud.GoogleCloudStorage",
"OPTIONS": {
@ -165,49 +155,36 @@ STORAGES = {
"default_acl": "publicRead",
},
},
{%- endif %}
{%- elif cookiecutter.cloud_provider == 'Azure' %}
"default": {
"BACKEND": "storages.backends.azure_storage.AzureStorage",
"OPTIONS": {
"location": "media",
"overwrite_files": False,
"file_overwrite": False,
},
},
{%- if cookiecutter.use_whitenoise == 'y' %}
"staticfiles": {
"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage",
},
{%- else %}
"staticfiles": {
"BACKEND": "storages.backends.azure_storage.AzureStorage",
"OPTIONS": {
"location": "static",
},
},
{%- endif %}
{%- endif %}
}
{%- endif %}
{%- if cookiecutter.cloud_provider == 'AWS' %}
MEDIA_URL = f"https://{aws_s3_domain}/media/"
{%- if cookiecutter.use_whitenoise == 'n' %}
COLLECTFASTA_STRATEGY = "collectfasta.strategies.boto3.Boto3Strategy"
COLLECTFAST_STRATEGY = "collectfast.strategies.boto3.Boto3Strategy"
STATIC_URL = f"https://{aws_s3_domain}/static/"
{%- endif %}
{%- elif cookiecutter.cloud_provider == 'GCP' %}
MEDIA_URL = f"https://storage.googleapis.com/{GS_BUCKET_NAME}/media/"
{%- if cookiecutter.use_whitenoise == 'n' %}
COLLECTFASTA_STRATEGY = "collectfasta.strategies.gcloud.GoogleCloudStrategy"
COLLECTFAST_STRATEGY = "collectfast.strategies.gcloud.GoogleCloudStrategy"
STATIC_URL = f"https://storage.googleapis.com/{GS_BUCKET_NAME}/static/"
{%- endif %}
{%- elif cookiecutter.cloud_provider == 'Azure' %}
MEDIA_URL = f"https://{AZURE_ACCOUNT_NAME}.blob.core.windows.net/media/"
{%- if cookiecutter.use_whitenoise == 'n' %}
STATIC_URL = f"https://{AZURE_ACCOUNT_NAME}.blob.core.windows.net/static/"
{%- endif %}
{%- endif %}
# EMAIL
# ------------------------------------------------------------------------------
@ -223,7 +200,6 @@ EMAIL_SUBJECT_PREFIX = env(
"DJANGO_EMAIL_SUBJECT_PREFIX",
default="[{{cookiecutter.project_name}}] ",
)
ACCOUNT_EMAIL_SUBJECT_PREFIX = EMAIL_SUBJECT_PREFIX
# ADMIN
# ------------------------------------------------------------------------------
@ -276,12 +252,12 @@ ANYMAIL = {
"SENDGRID_API_KEY": env("SENDGRID_API_KEY"),
"SENDGRID_API_URL": env("SENDGRID_API_URL", default="https://api.sendgrid.com/v3/"),
}
{%- elif cookiecutter.mail_service == 'Brevo' %}
# https://anymail.readthedocs.io/en/stable/esps/brevo/
EMAIL_BACKEND = "anymail.backends.brevo.EmailBackend"
{%- elif cookiecutter.mail_service == 'SendinBlue' %}
# https://anymail.readthedocs.io/en/stable/esps/sendinblue/
EMAIL_BACKEND = "anymail.backends.sendinblue.EmailBackend"
ANYMAIL = {
"BREVO_API_KEY": env("BREVO_API_KEY"),
"BREVO_API_URL": env("BREVO_API_URL", default="https://api.brevo.com/v3/"),
"SENDINBLUE_API_KEY": env("SENDINBLUE_API_KEY"),
"SENDINBLUE_API_URL": env("SENDINBLUE_API_URL", default="https://api.sendinblue.com/v3/"),
}
{%- elif cookiecutter.mail_service == 'SparkPost' %}
# https://anymail.readthedocs.io/en/stable/esps/sparkpost/
@ -309,8 +285,7 @@ COMPRESS_STORAGE = "compressor.storage.GzipCompressorFileStorage"
COMPRESS_STORAGE = STORAGES["staticfiles"]["BACKEND"]
{%- endif %}
# https://django-compressor.readthedocs.io/en/latest/settings/#django.conf.settings.COMPRESS_URL
COMPRESS_URL = STATIC_URL{% if cookiecutter.use_whitenoise == 'y' or cookiecutter.cloud_provider == 'None' %} # noqa: F405
{%- endif -%}
COMPRESS_URL = STATIC_URL{% if cookiecutter.use_whitenoise == 'y' or cookiecutter.cloud_provider == 'None' %}{% endif %}
{%- if cookiecutter.use_whitenoise == 'y' %}
# https://django-compressor.readthedocs.io/en/latest/settings/#django.conf.settings.COMPRESS_OFFLINE
COMPRESS_OFFLINE = True # Offline compression is required when using Whitenoise
@ -324,11 +299,11 @@ COMPRESS_FILTERS = {
"js": ["compressor.filters.jsmin.JSMinFilter"],
}
{% endif %}
{%- if cookiecutter.use_whitenoise == 'n' and cookiecutter.cloud_provider in ('AWS', 'GCP') -%}
# Collectfasta
{%- if cookiecutter.use_whitenoise == 'n' -%}
# Collectfast
# ------------------------------------------------------------------------------
# https://github.com/jasongi/collectfasta#installation
INSTALLED_APPS = ["collectfasta", *INSTALLED_APPS]
# https://github.com/antonagestam/collectfast#installation
INSTALLED_APPS = ["collectfast", *INSTALLED_APPS]
{% endif %}
# LOGGING
# ------------------------------------------------------------------------------

View File

@ -33,7 +33,7 @@ TEMPLATES[0]["OPTIONS"]["debug"] = True # type: ignore[index]
# MEDIA
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = "http://media.testserver/"
MEDIA_URL = "http://media.testserver"
{%- if cookiecutter.frontend_pipeline == 'Webpack' %}
# django-webpack-loader

View File

@ -1,3 +1,4 @@
# ruff: noqa
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
@ -42,7 +43,7 @@ urlpatterns += [
# API base url
path("api/", include("config.api_router")),
# DRF auth token
path("api/auth-token/", obtain_auth_token, name="obtain_auth_token"),
path("auth-token/", obtain_auth_token),
path("api/schema/", SpectacularAPIView.as_view(), name="api-schema"),
path(
"api/docs/",
@ -76,7 +77,4 @@ if settings.DEBUG:
if "debug_toolbar" in settings.INSTALLED_APPS:
import debug_toolbar
urlpatterns = [
path("__debug__/", include(debug_toolbar.urls)),
*urlpatterns,
]
urlpatterns = [path("__debug__/", include(debug_toolbar.urls))] + urlpatterns

View File

@ -1,3 +1,4 @@
# ruff: noqa
"""
WSGI config for {{ cookiecutter.project_name }} project.
@ -24,9 +25,16 @@ from django.core.wsgi import get_wsgi_application
# {{ cookiecutter.project_slug }} directory.
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent
sys.path.append(str(BASE_DIR / "{{ cookiecutter.project_slug }}"))
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)

View File

@ -1,16 +0,0 @@
services:
docs:
image: {{ cookiecutter.project_slug }}_local_docs
container_name: {{ cookiecutter.project_slug }}_local_docs
build:
context: .
dockerfile: ./compose/local/docs/Dockerfile
env_file:
- ./.envs/.local/.django
volumes:
- ./docs:/docs:z
- ./config:/app/config:z
- ./{{ cookiecutter.project_slug }}:/app/{{ cookiecutter.project_slug }}:z
ports:
- '9000:9000'
command: /start-docs

View File

@ -13,11 +13,11 @@ APP = /app
APP = ../{{cookiecutter.project_slug}}
{% endif %}
.PHONY: html livehtml apidocs Makefile
.PHONY: help livehtml apidocs Makefile
# Put it first so that "make" without argument is like "make html".
html:
@$(SPHINXBUILD) -M html "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -c .
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -c .
# Build, watch and serve docs with live reload
livehtml:

View File

@ -1,4 +1,4 @@
# ruff: noqa: ERA001, PTH100
# ruff: noqa
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
@ -13,10 +13,9 @@
import os
import sys
import django
if os.getenv("READTHEDOCS", default="False") == "True":
if os.getenv("READTHEDOCS", default=False) == "True":
sys.path.insert(0, os.path.abspath(".."))
os.environ["DJANGO_READ_DOT_ENV_FILE"] = "True"
os.environ["USE_DOCKER"] = "no"
@ -27,13 +26,16 @@ else:
sys.path.insert(0, os.path.abspath(".."))
{%- endif %}
os.environ["DATABASE_URL"] = "sqlite:///readthedocs.db"
{%- if cookiecutter.use_celery == 'y' %}
os.environ["CELERY_BROKER_URL"] = os.getenv("REDIS_URL", "redis://redis:6379")
{%- endif %}
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
django.setup()
# -- Project information -----------------------------------------------------
project = "{{ cookiecutter.project_name }}"
copyright = """{% now 'utc', '%Y' %}, {{ cookiecutter.author_name }}""" # noqa: A001
copyright = """{% now 'utc', '%Y' %}, {{ cookiecutter.author_name }}"""
author = "{{ cookiecutter.author_name }}"

View File

@ -15,7 +15,7 @@ from inside the `{{cookiecutter.project_slug}}/docs` directory.
{% else %}
To build and serve docs, use the commands::
docker compose -f docker-compose.local.yml up docs
docker compose -f local.yml up docs
{% endif %}
@ -26,7 +26,7 @@ Changes to files in `docs/_source` will be picked up and reloaded automatically.
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.
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.

Some files were not shown because too many files have changed in this diff Show More