Continuous integration for Django projects
Fullstack Developer and Tech Author
This tutorial sets up a continuous integration (CI) pipeline for a Django project on CircleCI. We start from a finished Django blog app, add tests, and build a pipeline that runs them on every push, first against SQLite and then against PostgreSQL. Along the way, we cache dependencies, publish test results to CircleCI, and add a status badge. Most of the steps apply to other Python projects too.
Django describes itself as “the web framework for perfectionists with deadlines.” Its test framework and ORM make it straightforward to run automated tests against a real database, which is what a CI pipeline needs. The code here uses Django 6.1 and Python 3.14, and the CircleCI configuration uses version: 2.1.
Prerequisites
Before starting, set up the following:
- Git
- Python 3.12, 3.13, or 3.14. Django 6.1 adds official support for Python 3.15 in version 6.1.3.
- Docker, including Docker Compose
- A GitHub account and a CircleCI account (the free plan is enough)
- The CircleCI CLI (installed later in this tutorial)
Set up the sample Django app
Django Girls offers a great tutorial on the Django framework. This tutorial uses the blog app built there, with a few additions, and sets up CircleCI for it. The app stores its data in a SQLite file.
Clone the repository and switch to its main branch:
git clone https://github.com/CIRCLECI-GWP/django-girls-complete.git
cd django-girls-complete
git checkout main
The repository keeps each stage of this tutorial on its own branch:
mainhas the finished Django Girls blog plus the Docker files. We start here.testsadds the tests from the next section.circleciadds the finished CircleCI configuration. It’s the default branch.
To skip a step, check out the matching branch before editing any files. Git won’t switch branches if the switch would overwrite uncommitted changes.
Compared with the Django Girls tutorial, the repository adds:
- A check that only logged-in users can add or edit posts
- An
.editorconfigfile for consistent coding styles - Files to run the app in Docker, covered later in this tutorial
- ruff for Python linting and formatting
- A README and a license
The original branch has the code as the Django Girls tutorial leaves it. The Django Girls tutorial currently uses Django 5.2, and this repository uses Django 6.1.
Create a virtual environment and install the dependencies:
python3 -m venv venv
. venv/bin/activate
pip install -r requirements.txt
The venv documentation lists the activation command for Windows shells.
requirements.txt lists Django and three packages the pipeline uses later: dj-database-url and psycopg for PostgreSQL, and pytest-django for test reports.
Django~=6.1.2
dj-database-url~=3.1
psycopg[binary]~=3.3
pytest-django~=4.14
The project follows Django’s standard layout. The mysite package holds the settings and URL configuration, and the blog app holds the models, views, forms, templates, and tests.
Write tests for the Django app
The pipeline needs tests to run, so that a broken change fails the build before it’s merged. Django’s test framework is documented in Writing and running tests.
Replace the contents of blog/tests.py with:
from django.contrib.auth.models import User
from django.test import TestCase
from django.utils import timezone
from .forms import PostForm
from .models import Post
class PostTestCase(TestCase):
def setUp(self):
self.user1 = User.objects.create_user(username='admin')
Post.objects.create(
author=self.user1,
title='Test',
text='We are testing this',
created_date=timezone.now(),
published_date=timezone.now(),
)
def test_post_is_posted(self):
"""Posts are created"""
post1 = Post.objects.get(title='Test')
self.assertEqual(post1.text, 'We are testing this')
def test_valid_form_data(self):
form = PostForm(
{
'title': 'Just testing',
'text': 'Repeated tests make the app foul-proof',
}
)
self.assertTrue(form.is_valid())
post1 = form.save(commit=False)
post1.author = self.user1
post1.save()
self.assertEqual(post1.title, 'Just testing')
self.assertEqual(post1.text, 'Repeated tests make the app foul-proof')
def test_blank_form_data(self):
form = PostForm({})
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors,
{
'title': ['This field is required.'],
'text': ['This field is required.'],
},
)
PostTestCase extends django.test.TestCase. Django runs these tests against a separate test database, so they never touch the data in db.sqlite3. The class has four methods:
setUpruns before each test. It creates a user,self.user1, and a published post by that user.test_post_is_postedchecks that the post titled Test has the text We are testing this.test_valid_form_datafills in aPostFormwith a title and text, saves the post, and checks both fields.test_blank_form_datachecks that an empty form is invalid and that both fields are reported as required.
Run the tests with Django’s test runner:
python manage.py test
The runner finds the tests in any file whose name starts with test and runs them:
Found 3 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
...
----------------------------------------------------------------------
Ran 3 tests in 0.002s
OK
Destroying test database for alias 'default'...
The CI job runs the same tests with pytest instead, because pytest can write a report that CircleCI reads. The repository’s pytest.ini tells pytest-django where the settings live:
[pytest]
DJANGO_SETTINGS_MODULE = mysite.settings
python_files = tests.py test_*.py *_tests.py
Run pytest to check that it finds the same three tests:
pytest
The output ends with:
blog/tests.py ... [100%]
============================== 3 passed in 0.07s ===============================
Commit the tests:
git add blog/tests.py
git commit -m "Add tests for the blog app"
The tests branch has the same file, so git diff origin/tests prints nothing.
Dockerize the app
Dockerizing the app packages it, with its dependencies, into an image that runs the same way on any machine with Docker. The repository includes four files for this:
Dockerfiledefines the image..dockerignorekeeps the virtual environment, Git metadata, and other local files out of the build context.docker-compose.ymlbuilds and runs the image with Docker Compose. It mounts the project folder into the container, so code changes show up without a rebuild.init.shresets the SQLite database, applies the migrations, and creates anadminuser with the passwordpasseach time the container starts.
Here’s the Dockerfile:
FROM python:3.14-slim
ENV PYTHONUNBUFFERED=1
WORKDIR /code
COPY requirements.txt /code/
RUN pip install -r requirements.txt
COPY . /code/
CMD ["sh", "-c", "sh init.sh && exec python3 manage.py runserver 0.0.0.0:8000"]
The image uses Python 3.14, the same version the CI pipeline uses. In the CMD, exec replaces the shell with the Django server, so the server receives the stop signal when the container stops and exits right away.
Start the app:
docker compose up
Then open http://localhost:8000 in a browser. To add or edit posts, log in at http://localhost:8000/admin/ as admin with the password pass.
Press Ctrl+C in the terminal to stop the app.
Add the CircleCI configuration
To run the tests on CircleCI, the project needs a configuration file. Create a .circleci folder in the project’s root, add a config.yml file to it, and paste in:
version: 2.1
jobs:
test:
docker:
- image: cimg/python:3.14
steps:
- checkout
- restore_cache:
keys:
- pip-cache-v1-{{ .Branch }}-{{ checksum "requirements.txt" }}
- pip-cache-v1-{{ .Branch }}-
- pip-cache-v1-
- run:
name: Install dependencies
command: pip install -r requirements.txt
- save_cache:
key: pip-cache-v1-{{ .Branch }}-{{ checksum "requirements.txt" }}
paths:
- ~/.cache/pip
- run:
name: Run tests
command: pytest --junitxml=test-results/junit.xml
- store_test_results:
path: test-results
workflows:
build-and-test:
jobs:
- test
Here’s what each part does:
version: 2.1selects the configuration format. It’s the only version CircleCI compiles: since September 21, 2026, pipelines that useversion: 2fail with “Config version 2 has reached end of life.”- The
testjob runs in a container built fromcimg/python:3.14, CircleCI’s Python convenience image, so CI uses the same Python version as theDockerfile. For fully reproducible builds, pin a full tag such ascimg/python:3.14.8. checkoutcopies the repository into the job’s working directory, over SSH for projects connected through the GitHub OAuth app and over HTTPS for projects connected through the GitHub App.restore_cacheandsave_cachekeep pip’s download cache between runs. The caching section explains the keys.- The
Install dependenciesstep runspip install. The image’s Python belongs to thecircleciuser, so the job doesn’t need a virtual environment. pytest --junitxml=test-results/junit.xmlruns the tests and writes a JUnit XML report, andstore_test_resultsuploads it. CircleCI uses the report to list each test in the job’s Tests tab.- The
build-and-testworkflow runs thetestjob on every push.
For more options, see the Python quickstart and Upload test results.
Commit the configuration:
git add .circleci/config.yml
git commit -m "Add CircleCI configuration"
Validate the config with the CircleCI CLI
The CircleCI CLI can check the configuration before anything is pushed. This tutorial uses CLI v1. If circleci version already prints a 0.1.x version, the machine has the legacy CLI, which doesn’t have the auth login and run watch commands used later. Uninstall it first, as the CLI guide describes. Then install CLI v1 with Homebrew. The CLI’s install page also lists WinGet, apt, rpm, and Snap packages.
brew install circleci
Then, from the project’s root, run:
circleci config validate
Config file at ".circleci/config.yml" is valid.
config validate doesn’t need a CircleCI login. It can pass a config that CircleCI then refuses to compile: CLI 1.9.0, for example, still accepts version: 2. circleci config validate --next also applies the compile rules CircleCI has enforced since September 21, 2026, and rejects that config.
Earlier versions of the CLI could also run a job on a local machine with circleci local execute or circleci build. CLI v1 removed local job execution, so the next step runs the pipeline on CircleCI itself.
Connect the project to CircleCI
CircleCI builds code from a repository on GitHub, so the project needs a repository of its own. On GitHub, create a new, empty repository named django-girls-complete, without a README, license, or .gitignore. Then point the clone at it and push main:
git remote rename origin upstream
git remote add origin https://github.com/<github-username>/django-girls-complete.git
git push -u origin main
Renaming the original remote to upstream keeps the tutorial’s tests and circleci branches available for comparison. For more on this step, see Pushing a project to GitHub.
Next, log in to the CircleCI web app, or sign up for free, and select the organization. The next steps depend on the organization’s type, which its URL in the web app shows: /circleci/ for organizations connected through the CircleCI GitHub App, and /github/ or /gh/ for organizations connected through the GitHub OAuth app.
- Organizations connected through the CircleCI GitHub App: on the Home page, select Create project, give the project a name, and select Next. Name the pipeline and choose the repository. The first time, select the GitHub Cloud tile, and CircleCI redirects to GitHub to install the CircleCI GitHub App. Keep the default trigger, which runs the pipeline on every commit to the repository. CircleCI then shows the
.circleci/config.ymlthat’s already in the repository. Select Review and check the setup. - Organizations connected through the GitHub OAuth app, which CircleCI creates when a user signs in with a GitHub account: select Projects in the sidebar, find the repository, and select Set up. Choose the Fastest option, which uses the
.circleci/config.ymlalready in the repository, entermainas the branch, and select Set Up Project.
From the terminal, circleci onboard does the same setup for either type of organization. See Create a project for details.
Depending on the flow, CircleCI either starts a run right away or waits for the next push to main. When the pipeline passes, select the test job, then the Tests tab, to see the three tests from the JUnit report:
Run Django tests against PostgreSQL in CircleCI
SQLite is fine for local development, but many Django projects run PostgreSQL in production, and some behavior differs between database backends. CircleCI can start a PostgreSQL server next to the job as a service container, so the tests run against PostgreSQL too.
The sample project is ready for this. Its settings read the database from a DATABASE_URL environment variable using dj-database-url, and fall back to the SQLite file when the variable isn’t set:
DATABASES = {
'default': dj_database_url.config(default=f'sqlite:///{BASE_DIR / "db.sqlite3"}'),
}
requirements.txt also includes psycopg 3, the PostgreSQL driver Django recommends.
Replace .circleci/config.yml with this version:
version: 2.1
jobs:
test:
docker:
# Primary container: every step runs here.
- image: cimg/python:3.14
environment:
DATABASE_URL: postgresql://postgres@localhost/circle_test
# Service container: PostgreSQL, reachable on localhost.
- image: cimg/postgres:18.6
environment:
POSTGRES_USER: postgres
steps:
- checkout
- restore_cache:
keys:
- pip-cache-v1-{{ .Branch }}-{{ checksum "requirements.txt" }}
- pip-cache-v1-{{ .Branch }}-
- pip-cache-v1-
- run:
name: Install dependencies
command: pip install -r requirements.txt
- save_cache:
key: pip-cache-v1-{{ .Branch }}-{{ checksum "requirements.txt" }}
paths:
- ~/.cache/pip
- run:
name: Wait for PostgreSQL
command: dockerize -wait tcp://localhost:5432 -timeout 1m
- run:
name: Run tests
command: pytest --junitxml=test-results/junit.xml
- store_test_results:
path: test-results
workflows:
build-and-test:
jobs:
- test
Compared with the first version:
- A second image,
cimg/postgres:18.6, runs PostgreSQL 18 next to the job, reachable atlocalhost. The image creates a database namedcircle_test, andPOSTGRES_USER: postgrescreates thepostgresrole to connect with. DATABASE_URLon the primary container points Django at that database. During the run, Django’s test runner creates and then drops its owntest_circle_testdatabase.- The
Wait for PostgreSQLstep runsdockerize, which comes preinstalled in CircleCI’s convenience images, to wait until PostgreSQL accepts connections before the tests start.
Commit the change and log in to CircleCI from the terminal. circleci auth login opens a browser to log in, and is only needed once:
git add .circleci/config.yml
git commit -m "Run the tests against PostgreSQL"
circleci auth login
If the organization’s slug starts with circleci/, as it does for organizations connected through the CircleCI GitHub App (the ones with /circleci/ in their URL), run circleci project link in the repository now. The CLI can’t find these projects from the Git remote, so project link records the project’s IDs in .circleci/info.yml. Then push the commit and follow the run:
git push && circleci run watch --sha $(git rev-parse HEAD)
circleci run watch waits for the run that the push started and exits with status 0 when it succeeds.
The finished configuration is on the circleci branch, so git diff upstream/circleci -- .circleci/config.yml prints nothing.
Cache dependencies between runs
Every job starts in a fresh container, so without a cache, pip install downloads every package on every run. The configuration’s cache steps keep pip’s download cache, ~/.cache/pip, between runs (see Caching dependencies):
save_cachestores the folder under a key that ends in{{ checksum "requirements.txt" }}, so the key changes whenever the dependencies do. CircleCI never overwrites a cache. A later run that produces the same key skips the save.restore_cachetries its keys in order. The first matches only this branch and this exactrequirements.txt. The other two are fallbacks that restore the newest cache for the branch, or for any branch, after the requirements change. That’s safe for a download cache, because pip still installs exactly whatrequirements.txtasks for and downloads anything that’s missing.v1is a version marker. Change it tov2in both steps to start over with an empty cache.
To see the cache at work, rerun the workflow from the start, either from the rerun menu on the pipelines page or with circleci workflow rerun <workflow-id>. On the first run, the Restoring cache step finds nothing and Saving cache uploads about 40 MiB. On the rerun, Restoring cache reports Found a cache, pip prints Using cached for every package, and Saving cache skips the upload because the key already exists.
For a project this small, the cache doesn’t make a measurable difference. In our runs, Install dependencies took 6.2 seconds with an empty cache and 7.6 seconds with a warm one, because downloading a handful of small packages is already quick. The cache pays off as the dependency list grows, and most of all for packages pip has to build from source, because pip caches the wheels it builds. Caching the installed packages saves more time, but CircleCI’s caching guide only recommends that with a lock file that pins every version. The python orb’s install-packages command also caches installed packages, and adds the Python version to its cache key.
Add a status badge
A status badge in the README shows whether the latest pipeline on a branch passed. To get the badge code:
- In the CircleCI web app, select Projects, select the ellipsis (…) next to the project, and choose Project Settings. The project’s overview page also has a Settings link.
- Select Status Badges in the sidebar.
- Choose the branch, for example
main. For a private repository, select Add API token so the badge can read the status. - Choose a format, such as Markdown, and select Copy.
Paste the code near the top of the README, after the project description. Status badges covers the other formats and styles.
Conclusion
The Django project now has a working CI pipeline. Every push runs the tests on CircleCI against PostgreSQL, the results show up in the Tests tab, pip’s download cache carries over between runs, and the README badge shows the latest status. The same approach works for most Python projects: a cimg/python image for the job, plus a service container for anything the tests depend on.
A next step is a deployment job that runs after test passes on main. Workflows support that ordering with requires and branch filters.