Home >Backend Development >Python Tutorial >Django Heroku: complete deployment guide �

Django Heroku: complete deployment guide �

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-29 10:12:12277browse

Django   Heroku : Guide Complet de Déploiement �

This complete guide explains step by step how to deploy a Django application on Heroku and configure a postgreSql database.

Prerequisites:

Before you start, check that you have:

  • Python 3.x
  • git
  • A heroku account
  • a local functional django application
  • The HEROKU command line interface (Heroku CLI)

Project preparation:

  1. Project structure: Your project must look like this:
<code>my_project/
├── manage.py
├── my_project/
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── requirements.txt
└── Procfile</code>
  1. Configuration of dependencies:

Create the requirements.txt:

file
<code class="language-bash">pip freeze > requirements.txt</code>

Add the following outbuildings:

<code>django
gunicorn
psycopg2-binary
django-environ
whitenoise
dj-database-url</code>
  1. Django configuration for Heroku:

Modify the settings.py:

file
<code class="language-python">import os
import dj_database_url
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = os.environ.get('SECRET_KEY', 'votre-clé-secrète-par-défaut')

DEBUG = os.environ.get('DEBUG', 'True') == 'True'

ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '').split(',')

DATABASES = {
    'default': dj_database_url.config(
        default=os.environ.get('DATABASE_URL', 'sqlite:///db.sqlite3'),
        conn_max_age=600
    )
}

STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

MIDDLEWARE = [
    # ...
    'whitenoise.middleware.WhiteNoiseMiddleware',
]</code>
  1. Creation of the procile:

Create a Procfile file to the project root with the following content:

<code>web: gunicorn my_project.wsgi</code>

Deployment on Heroku:

  1. Creation of the Heroku application:
<code class="language-bash">heroku create mon-app-django</code>
  1. Configuration of environment variables:
<code class="language-bash">heroku config:set SECRET_KEY='votre-clé-secrète'
heroku config:set DEBUG='False'
heroku config:set ALLOWED_HOSTS='.herokuapp.com'</code>
  1. Postgresql database: (continued in the next section)

The above is the detailed content of Django Heroku: complete deployment guide �. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn