DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Enhance Terraform Final Plan Output in GitHub Actions
  • How To Build a Simple GitHub Action To Deploy a Django Application to the Cloud
  • Continuous Integration for iOS and macOS: Low-Code Self-Hosted Runner for Xcode Project Automation
  • Delivering Your Code to the Cloud With JFrog Artifactory and GitHub Actions

Trending

  • Agile and Quality Engineering: A Holistic Perspective
  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis
  • Stateless vs Stateful Stream Processing With Kafka Streams and Apache Flink
  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. Automating Django Deployments: Integrating CI/CD With GitHub Actions and Heroku

Automating Django Deployments: Integrating CI/CD With GitHub Actions and Heroku

This guide will walk you through setting up a basic CI/CD pipeline using GitHub Actions, a popular CI/CD tool that integrates seamlessly with GitHub repositories.

By 
Vijay Panwar user avatar
Vijay Panwar
DZone Core CORE ·
Mar. 04, 24 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
3.0K Views

Join the DZone community and get the full member experience.

Join For Free

Implementing Continuous Integration/Continuous Deployment (CI/CD) for a Python application using Django involves several steps to automate testing and deployment processes. This guide will walk you through setting up a basic CI/CD pipeline using GitHub Actions, a popular CI/CD tool that integrates seamlessly with GitHub repositories.

Step 1: Setting up Your Django Project

Ensure your Django project is in a Git repository hosted on GitHub. This repository will be the basis for setting up your CI/CD pipeline.

Step 2: Creating a Virtual Environment and Dependencies File

1. Virtual Environment

It's good practice to use a virtual environment for your Django project to manage dependencies.

PowerShell
 
python3 -m venv venv

source venv/bin/activate  # On Windows use `venv\Scripts\activate`


2. Dependencies File

Create a `requirements.txt` file in your project root that lists all your project's dependencies, including Django itself.

PowerShell
 
pip freeze > requirements.txt


Step 3: Configuring GitHub Actions for Continuous Integration

1. Create a Workflow File

In your repository, create a directory and file for your GitHub Actions workflow: `.github/workflows/django-ci.yml`.

2. Define the Workflow

Populate `django-ci.yml` with the necessary steps to install dependencies, run tests, and any other checks you want as part of your CI process. Here's a simple example:

Here's a breakdown of each section in the `django-ci.yml` file:

YAML
 
name: Django CI



on: [push, pull_request]


  • name: This is a descriptive name for your workflow. It will appear in the GitHub Actions section of your repository.
  • on: This key specifies the events that will trigger the workflow. In this case, the workflow runs on `push` events to any branch and on `pull_request` events.
YAML
 
jobs:

  build:

    runs-on: ubuntu-latest


  • jobs: Jobs are a set of steps that execute on the same runner. Here, we have a job named `build`.
  • build: This is the identifier for the job. You can name it anything, but `build` is descriptive of its purpose.
  • runs-on: Specifies the type of machine to run the job on. `ubuntu-latest` means the job will run on the latest version of Ubuntu Linux.
YAML
 
steps:

- uses: actions/checkout@v2

- name: Set up Python 3.x

  uses: actions/setup-python@v2

  with:

    python-version: 3.x


  • steps: Steps are individual tasks that run commands in the job. Each step can either run a script or an action.
  • uses: actions/checkout@v2: This step uses the `checkout` action to check out your repository under `$GITHUB_WORKSPACE`, so your workflow can access it.
  • uses: actions/setup-python@v2: This action sets up a Python environment for the job, specifying that we want to use Python 3.x.
YAML
 
- name: Install Dependencies

  run: |

    python -m pip install --upgrade pip

    pip install -r requirements.txt

 

  • name: Provides a descriptive name for the step.
  • run: Executes command-line programs. Here, it's used to upgrade `pip` and install the dependencies listed in `requirements.txt`.
YAML
 
- name: Run Django Tests

  run: |

    python manage.py test


Run Django Tests: This step runs the Django test suite by executing `manage.py test`. This is where your Django application's unit tests are executed, ensuring that your codebase works as expected.

Step 4: Configuring Continuous Deployment

Continuous Deployment can be configured to automatically deploy your Django application to a hosting service like Heroku, AWS, or any other provider you choose. For this example, we'll use Heroku.

Preparing Your Django Project for Heroku Deployment

Before integrating the deployment process into your CI/CD pipeline, ensure your Django project is prepared for Heroku deployment. This preparation includes:

1. Procfile

Create a `Procfile` in the root directory of your Django project. This file tells Heroku how to run your application. For a typical Django app, the `Procfile` might look like this:

Plain Text
 
web: gunicorn myproject.wsgi --log-file -

  

Replace `myproject` with the name of your Django project.

2. Runtime Specification

If your application requires a specific Python version, specify this version in a `runtime.txt` file in your project's root directory, like so:

Plain Text
 
 python-3.9.1


Note: Any Python version python-3.x

3. Database Configuration

Make sure your `settings.py` is configured to use Heroku's database when deployed. Heroku sets an environment variable called `DATABASE_URL` for the database, which you can use with `dj-database-url`:

Plain Text
 
import dj_database_url

DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True)


Extending the GitHub Actions Workflow for Deployment

After preparing your Django project for Heroku deployment, extend your `.github/workflows/django-ci.yml` file to include deployment steps. Here's how you can do it:

YAML
 
- name: Install Heroku CLI

  run: |

    curl https://cli-assets.heroku.com/install.sh | sh



- name: Deploy to Heroku

  if: github.ref == 'refs/heads/main'

  run: |

    heroku git:remote -a ${{ secrets.HEROKU_APP_NAME }}

    git push heroku HEAD:master -f

  env:

    HEROKU_API_KEY: ${{ secrets.HEROKU_API_KEY }}


Breakdown

1. Install Heroku CLI

This step installs the Heroku Command Line Interface on the runner, which allows you to interact with Heroku from the command line.

2. Deploy to Heroku

  • Conditional Execution: The `if: github.ref == 'refs/heads/main'` condition ensures that the deployment only occurs when changes are pushed to the `main` branch.
  • Heroku Remote Setup:`heroku git:remote -a ${{ secrets.HEROKU_APP_NAME }}` sets the Heroku app as a remote for git. Replace `HEROKU_APP_NAME` with the name of your Heroku app.
  • Deployment: `git push heroku HEAD:master -f` pushes the code to Heroku, triggering a deployment. The `-f` flag forces the push, which might be necessary if you're overwriting history.

Managing Secrets for Heroku Deployment

For the deployment steps to work, you need to configure the`HEROKU_API_KEY` and `HEROKU_APP_NAME` as secrets in your GitHub repository:

  1. Go to your repository on GitHub, click on "Settings" > "Secrets".
  2. Click on "New repository secret."
  3. Add `HEROKU_API_KEY` as the name and your Heroku API key as the value. Repeat the process for `HEROKU_APP_NAME`, adding your Heroku app's name as the value.

Step 5: Managing Secrets

GitHub Secrets

Navigate to your repository settings on GitHub, find the "Secrets" section, and add your Heroku API key (`HEROKU_API_KEY`) and app name (`HEROKU_APP_NAME`) as secrets.

Conclusion

This guide outlines the basic steps to set up a CI/CD pipeline for a Django application using GitHub Actions, from automated testing to deployment on Heroku. The CI process ensures your code is automatically tested, while the CD process enables seamless deployment to your hosting platform, ensuring your application is always up-to-date with the latest changes in your codebase.

Cheers, Happy Coding!!

GitHub Django (web framework) Continuous Integration/Deployment

Opinions expressed by DZone contributors are their own.

Related

  • Enhance Terraform Final Plan Output in GitHub Actions
  • How To Build a Simple GitHub Action To Deploy a Django Application to the Cloud
  • Continuous Integration for iOS and macOS: Low-Code Self-Hosted Runner for Xcode Project Automation
  • Delivering Your Code to the Cloud With JFrog Artifactory and GitHub Actions

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!