Getting Started on Heroku with Python
Introduction
Complete this tutorial to deploy a sample Python app to Cedar, the legacy generation of the Heroku platform. To deploy the app to the Fir generation, only available to Heroku Private Spaces, follow this guide instead.
The tutorial assumes that you have:
- A verified Heroku Account
- Python version 3.10 or newer (ideally 3.13) installed locally - see the installation guides for macOS, Windows, and Linux.
- An Eco dynos plan subscription (recommended)
Using dynos and databases to complete this tutorial counts towards your usage. We recommend using our low-cost plans to complete this tutorial. Eligible students can apply for platform credits through our new Heroku for GitHub Students program.
Set Up
The Heroku CLI requires Git, the popular version control system. If you don’t already have Git installed, complete the following before proceeding:
Install the Heroku Command Line Interface (CLI). Use the CLI to manage and scale your app, provision add-ons, view your logs, and run your app locally.
Download and run the installer for your platform:
$ brew tap heroku/brew && brew install heroku
Download the appropriate installer for your Windows installation:
More installation options for the Heroku CLI can be found here.
After installation, you can use the heroku
command from your command shell.
To log in to the Heroku CLI, use the heroku login
command:
$ heroku login
heroku: Press any key to open up the browser to login or q to exit:
Opening browser to https://cli-auth.heroku.com/auth/cli/browser/***
heroku: Waiting for login...
Logging in... done
Logged in as me@example.com
This command opens your web browser to the Heroku login page. If your browser is already logged in to Heroku, click the Log In
button on the page.
This authentication is required for the heroku
and git
commands to work correctly.
If you have any problems installing or using the Heroku CLI, see the main Heroku CLI article for advice and troubleshooting steps.
If you’re behind a firewall that uses a proxy to connect with external HTTP/HTTPS services, set the HTTP_PROXY
or HTTPS_PROXY
environment variables in your local development environment before running the heroku
command.
Clone the Sample App
If you’re new to Heroku, it’s recommended that you complete this tutorial using the Heroku-provided sample application.
To deploy an existing application, follow the Preparing a Codebase for Heroku Deployment article instead.
Clone the sample application to get a local version of the code. Execute these commands in your local command shell or terminal:
$ git clone https://github.com/heroku/python-getting-started.git
$ cd python-getting-started
You now have a functioning Git repository that contains a simple Python app, that uses the web framework Django. It includes a .python-version
file specifying the Python version to use and a requirements.txt
, used by Python’s dependency manager, pip.
Define a Procfile
Use a Procfile, a text file in the root directory of your application, to explicitly declare what command to execute to start your app.
The Procfile
in the example app looks like this:
web: gunicorn --config gunicorn.conf.py gettingstarted.wsgi
This Procfile declares a process type web
and the command needed to run it. The name web
is important here because it declares that this process type attaches to Heroku’s HTTP routing stack and receives web traffic when deployed. The command used here runs Gunicorn, the web server, and passes in a configuration file.
A Procfile can contain additional process types. For example, you can declare a background worker process that processes items off a queue.
Microsoft Windows
The sample app has an additional Procfile
for local development on Microsoft Windows, located in the file Procfile.windows
. Later tutorial steps use this instead to start a different web server compatible with Windows.
web: python manage.py runserver %PORT%
Create and Deploy the App
Using a dyno and a database to complete this tutorial counts towards your usage. Delete your app, and database as soon as you’re done to control costs.
By default, apps use Eco dynos if you’re subscribed to Eco. Otherwise, it defaults to Basic dynos. The Eco dynos plan is shared across all Eco dynos in your account and is recommended if you plan on deploying many small apps to Heroku. Learn more here. Eligible students can apply for platform credits through our Heroku for GitHub Students program.
To prepare Heroku to receive your source code, create an app:
$ heroku create
Creating app... done, ⬢ serene-caverns-82714
https://serene-caverns-82714.herokuapp.com/ | https://git.heroku.com/serene-caverns-82714.git
When you create an app, a git remote called heroku
is also created and associated with your local git repository. Git remotes are versions of your repository that live on other servers. You deploy your app by pushing its code to that special Heroku-hosted remote associated with your app.
Heroku generates a random name for your app, in this case, serene-caverns-82714
. You can specify your own app name.
Deploy your code. This command pushes the main
branch of the sample repo to your heroku
remote, which then deploys to Heroku:
$ git push heroku main
Enumerating objects: 673, done.
Counting objects: 100% (673/673), done.
Delta compression using up to 10 threads
Compressing objects: 100% (315/315), done.
Writing objects: 100% (673/673), 141.61 KiB | 141.61 MiB/s, done.
Total 673 (delta 305), reused 673 (delta 305), pack-reused 0
remote: Resolving deltas: 100% (305/305), done.
remote: Updated 30 paths from a933377
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Building on the Heroku-24 stack
remote: -----> Determining which buildpack to use for this app
remote: -----> Python app detected
remote: -----> Using Python 3.13 specified in .python-version
remote: -----> Installing Python 3.13.0
remote: -----> Installing pip 24.0
remote: -----> Installing dependencies using 'pip install -r requirements.txt'
remote: Collecting django<5.2,>=5.1 (from -r requirements.txt (line 1))
remote: Downloading Django-5.1.3-py3-none-any.whl.metadata (4.2 kB)
remote: Collecting gunicorn<24,>=23 (from -r requirements.txt (line 2))
remote: Downloading gunicorn-23.0.0-py3-none-any.whl.metadata (4.4 kB)
remote: Collecting dj-database-url<3,>=2 (from -r requirements.txt (line 3))
remote: Downloading dj_database_url-2.3.0-py3-none-any.whl.metadata (12 kB)
remote: Collecting whitenoise<7,>=6 (from whitenoise[brotli]<7,>=6->-r requirements.txt (line 4))
remote: Downloading whitenoise-6.8.2-py3-none-any.whl.metadata (3.6 kB)
remote: Collecting asgiref<4,>=3.8.1 (from django<5.2,>=5.1->-r requirements.txt (line 1))
remote: Downloading asgiref-3.8.1-py3-none-any.whl.metadata (9.3 kB)
remote: Collecting sqlparse>=0.3.1 (from django<5.2,>=5.1->-r requirements.txt (line 1))
remote: Downloading sqlparse-0.5.2-py3-none-any.whl.metadata (3.9 kB)
remote: Collecting packaging (from gunicorn<24,>=23->-r requirements.txt (line 2))
remote: Downloading packaging-24.2-py3-none-any.whl.metadata (3.2 kB)
remote: Collecting typing-extensions>=3.10.0.0 (from dj-database-url<3,>=2->-r requirements.txt (line 3))
remote: Downloading typing_extensions-4.12.2-py3-none-any.whl.metadata (3.0 kB)
remote: Collecting brotli (from whitenoise[brotli]<7,>=6->-r requirements.txt (line 4))
remote: Downloading Brotli-1.1.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (5.5 kB)
remote: Downloading Django-5.1.3-py3-none-any.whl (8.3 MB)
remote: Downloading gunicorn-23.0.0-py3-none-any.whl (85 kB)
remote: Downloading dj_database_url-2.3.0-py3-none-any.whl (7.8 kB)
remote: Downloading whitenoise-6.8.2-py3-none-any.whl (20 kB)
remote: Downloading asgiref-3.8.1-py3-none-any.whl (23 kB)
remote: Downloading sqlparse-0.5.2-py3-none-any.whl (44 kB)
remote: Downloading typing_extensions-4.12.2-py3-none-any.whl (37 kB)
remote: Downloading Brotli-1.1.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.9 MB)
remote: Downloading packaging-24.2-py3-none-any.whl (65 kB)
remote: Installing collected packages: brotli, whitenoise, typing-extensions, sqlparse, packaging, asgiref, gunicorn, django, dj-database-url
remote: Successfully installed asgiref-3.8.1 brotli-1.1.0 dj-database-url-2.3.0 django-5.1.3 gunicorn-23.0.0 packaging-24.2 sqlparse-0.5.2 typing-extensions-4.12.2 whitenoise-6.8.2
remote: -----> $ python manage.py collectstatic --noinput
remote: WARNING:root:No DATABASE_URL environment variable set, and so no databases setup
remote: 1 static file copied to '/tmp/build_7b27a40d/staticfiles', 1 post-processed.
remote:
remote: -----> Discovering process types
remote: Procfile declares types -> web
remote:
remote: -----> Compressing...
remote: Done: 28.3M
remote: -----> Launching...
remote: Released v3
remote: https://serene-caverns-82714.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/serene-caverns-82714.git
* [new branch] main -> main
The app is now deployed. Ensure that at least one instance of the app is running:
$ heroku ps:scale web=1
If you see the error Couldn't find that process type (web)
when running the ps:scale
, it means your app is still deploying. Wait a few minutes and try again.
Visit the app at the URL shown in the logs. As a shortcut, you can also open the website as follows:
$ heroku open
View Logs
Heroku treats logs as streams of time-ordered events, aggregated from the output streams of all your app and Heroku components. Heroku provides a single stream for all events. View information about your running app by using one of the logging commands:
$ heroku logs --tail
2024-11-26T10:45:45.914677+00:00 heroku[web.1]: Starting process with command `gunicorn --config gunicorn.conf.py gettingstarted.wsgi`
2024-11-26T10:45:46.394639+00:00 app[web.1]: Python buildpack: Detected 512 MB available memory and 8 CPU cores.
2024-11-26T10:45:46.394711+00:00 app[web.1]: Python buildpack: Defaulting WEB_CONCURRENCY to 2 based on the available memory.
2024-11-26T10:45:46.646680+00:00 app[web.1]: WARNING:root:No DATABASE_URL environment variable set, and so no databases setup
2024-11-26T10:45:46.658628+00:00 app[web.1]: [2024-11-26 10:45:46 +0000] [2] [INFO] Starting gunicorn 23.0.0
2024-11-26T10:45:46.659030+00:00 app[web.1]: [2024-11-26 10:45:46 +0000] [2] [INFO] Listening at: http://[::]:45127 (2)
2024-11-26T10:45:46.659078+00:00 app[web.1]: [2024-11-26 10:45:46 +0000] [2] [INFO] Using worker: gthread
2024-11-26T10:45:46.661895+00:00 app[web.1]: [2024-11-26 10:45:46 +0000] [8] [INFO] Booting worker with pid: 8
2024-11-26T10:45:46.676834+00:00 app[web.1]: [2024-11-26 10:45:46 +0000] [9] [INFO] Booting worker with pid: 9
2024-11-26T10:45:47.011185+00:00 heroku[web.1]: State changed from starting to up
2024-11-26T10:45:57.197212+00:00 heroku[router]: at=info method=GET path="/" host=serene-caverns-82714.herokuapp.com request_id=6993babe-09d5-442c-b6be-099d82e7f38c fwd="123.456.789.0" dyno=web.1 connect=0ms service=10ms status=200 bytes=7809 protocol=https
To generate more log messages, refresh the app’s homepage in your browser.
To stop streaming the logs, press Control+C
.
Scale the App
After deploying the sample app, it automatically runs on a single web dyno. Think of a dyno as a lightweight container that runs the command specified in the Procfile
.
You can check how many dynos are running using the ps
command:
$ heroku ps
Eco dyno hours quota remaining this month: 999h 50m (99%)
Eco dyno usage for this app: 0h 0m (0%)
For more information on dyno sleeping and how to upgrade, see:
https://devcenter.heroku.com/articles/dyno-sleeping
=== web (Eco): gunicorn --config gunicorn.conf.py gettingstarted.wsgi (1)
web.1: up 2024/08/09 10:47:46 +0100 (~ 4m ago)
Scaling an application on Heroku is equivalent to changing the number of running dynos. Scale the number of web dynos to zero:
$ heroku ps:scale web=0
Scaling dynos... done, now running web at 0:Eco
Access the app again by hitting refresh on the web tab, or heroku open
to open it in a web tab. You get an error message because you no longer have any web dynos available to serve requests.
Scale it up again:
$ heroku ps:scale web=1
Scaling dynos... done, now running web at 1:Eco
By default, apps use Eco dynos if you’re subscribed to Eco. Otherwise, it defaults to Basic dynos. The Eco dynos plan is shared across all Eco dynos in your account and is recommended if you plan on deploying many small apps to Heroku. Eco dynos sleep if they don’t receive any traffic for half an hour. This sleep behavior causes a few seconds delay for the first request upon waking. Eco dynos consume from a monthly, account-level quota of eco dyno hours. As long as you haven’t exhausted the quota, your apps can continue to run.
To avoid dyno sleeping, upgrade to a Basic or higher dyno type as described in the Dyno Types article. Upgrading to at least Standard dynos allows you to scale up to multiple dynos per process type.
Install App Dependencies Locally
Heroku recognizes an app as a Python app by looking for key files. Including a requirements.txt
in the root directory is one way we recognize your Python app.
The demo app you deployed already has a requirements.txt
:
django>=5.1,<5.2
gunicorn>=23,<24
dj-database-url>=2,<3
whitenoise[brotli]>=6,<7
The requirements.txt
file lists the app’s dependencies. When you deploy an app on Heroku, the Python buildpack installs these dependencies using the pip install
command.
To run the app locally, you must also install dependencies locally.
Before you do this, you must create and activate a virtual environment, also known as a venv
. This environment lets you install the packages without affecting your system Python installation.
First, check that your local Python version:
$ python3 --version
If your Python version is older than 3.10 you must install a newer version of Python before creating a virtual environment. See the Python installation guides for macOS, Windows, and Linux.
Create a virtual environment inside the example app directory with this command:
$ python3 -m venv --upgrade-deps .venv
Next, activate the virtual environment:
If you’re on a Microsoft Windows system, activate with:
.\.venv\Scripts\activate
Or if you’re on a macOS/Linux system, activate with:
$ source .venv/bin/activate
For help with setting up a virtual environment, see the Python documentation.
Finally, install the dependencies into the newly created environment:
$ pip install -r requirements.txt
Installing the dependencies also installs their dependencies. View all installed packages using pip list
:
$ pip list
Package Version
----------------- -------
asgiref 3.8.1
Brotli 1.1.0
dj-database-url 2.3.0
Django 5.1.3
gunicorn 23.0.0
packaging 24.2
pip 24.3.1
sqlparse 0.5.2
typing_extensions 4.12.2
whitenoise 6.8.2
After installing dependencies, you can run your app locally.
Run the App Locally
Start your application locally using the heroku local
command, which is a part of the Heroku CLI.
If you’re on a Microsoft Windows system, run this:
$ heroku local --port 5006 -f Procfile.windows
Or if you’re on a macOS/Linux system, use the default Procfile
by running:
$ heroku local --port 5006
Running the command starts up the local web server:
[OKAY] Loaded ENV .env File as KEY=VALUE Format
11:01:34 AM web.1 | [2024-11-26 11:01:34 +0000] [12487] [INFO] Starting gunicorn 23.0.0
11:01:34 AM web.1 | [2024-11-26 11:01:34 +0000] [12487] [INFO] Listening at: http://[::]:5006 (12487)
11:01:34 AM web.1 | [2024-11-26 11:01:34 +0000] [12487] [INFO] Using worker: gthread
11:01:34 AM web.1 | [2024-11-26 11:01:34 +0000] [12488] [INFO] Booting worker with pid: 12488
If you see an error when running heroku local
, check that you have installed the app’s dependencies locally and the virtual environment is still activated.
Just like Heroku, heroku local
uses the Procfile
to know what command to execute.
Open http://localhost:5006 with your web browser. You should see your app running locally.
To stop the app from running locally, go back to your terminal window and press Ctrl
+C
to exit.
Push Local Changes
In this step, you propagate a local change to the application to Heroku.
Add the requests
package to your requirements.txt
file:
django>=5.1,<5.2
gunicorn>=23,<24
dj-database-url>=2,<3
whitenoise[brotli]>=6,<7
requests
Use pip to install the requests
package via the updated requirements.txt
file:
$ pip install -r requirements.txt
Modify hello/views.py
to import the requests
module and the Django HttpResponse
class at the top of the file:
import requests
from django.http import HttpResponse
Now modify the index
method to use the module. Try replacing the current index
method with the following code:
def index(request):
r = requests.get('https://httpbin.org/status/418', timeout=10)
return HttpResponse('<pre>' + r.text + '</pre>')
Now test again locally.
If you’re on a Microsoft Windows system, run this:
$ heroku local --port 5006 -f Procfile.windows
Or if you’re on a macOS/Linux system, use the default Procfile
by running:
$ heroku local --port 5006
Visit your application at http://localhost:5006. If your changes worked, you will see the output of fetching https://httpbin.org/status/418:
-=[ teapot ]=-
_...._
.' _ _ `.
| ."` ^ `". _,
\_;`"---"`|//
| ;/
\_ _/
`"""`
If you see the error Internal Server Error
in your browser, and the error ModuleNotFoundError: No module named 'requests'
in the terminal log output, check that the requests
package installed successfully.
Now deploy this local change to Heroku.
Almost every deploy to Heroku follows this same pattern. First, add the modified files to the local Git repository:
$ git add .
Now commit the changes to the repository:
$ git commit -m "Updated index view"
Now deploy as before:
$ git push heroku main
Finally, check that everything is working:
$ heroku open
Provision a Logging Add-on
Add-ons are third-party cloud services that provide out-of-the-box additional services for your application, from persistence through logging to monitoring and more.
By default, Heroku stores 1500 lines of logs from your application, but the full log stream is available as a service. Several add-on providers have logging services that provide things such as log persistence, search, and email and SMS alerts.
In this step, you provision one of these logging add-ons, Papertrail.
Provision the Papertrail logging add-on:
$ heroku addons:create papertrail
Creating papertrail on ⬢ serene-caverns-82714... free
Welcome to Papertrail. Questions and ideas are welcome (technicalsupport@solarwinds.com). Happy logging!
Created papertrail-convex-88929 as PAPERTRAIL_API_TOKEN
Use heroku addons:docs papertrail to view documentation
The add-on is now deployed and configured for your application. You can list add-ons for your app with this command:
$ heroku addons
To see this particular add-on in action, visit your application’s Heroku URL a few times. Each visit generates more log messages, which get routed to the Papertrail add-on. Visit the Papertrail console to see the log messages:
$ heroku addons:open papertrail
Your browser opens up a Papertrail web console that shows the latest log events. The interface lets you search and set up alerts.
Start a Console
You can run a command, typically scripts and applications that are part of your app, in a one-off dyno using the heroku run
command. You can also launch a REPL process attached to your local terminal for experimenting in your app’s environment:
$ heroku run python manage.py shell
Running python manage.py shell on ⬢ serene-caverns-82714... up, run.9594 (Eco)
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
If you receive an error, Error connecting to process
, configure your firewall.
The Python shell runs in the context of your app and all its dependencies. From here, you can import some of your application files. For example, you can run:
>>> import requests
>>> r = requests.get('https://httpbin.org/status/418', timeout=10)
>>> print(r.text)
-=[ teapot ]=-
_...._
.' _ _ `.
| ."` ^ `". _,
\_;`"---"`|//
| ;/
\_ _/
`"""`
Run the command exit()
to exit the Python shell and terminate the dyno.
Let’s try another example. Create another one-off dyno and run the bash
command to open up a shell on that dyno. You can then execute commands there. Each dyno has its own ephemeral filespace, populated with your app and its dependencies. After the command completes, in this case, bash
, the dyno terminates:
$ heroku run bash
Running bash on ⬢ serene-caverns-82714... up, run.3789 (Eco)
~ $ ls -A
app.json .env .github hello manage.py Procfile.windows .python-version requirements.txt
.cache gettingstarted .gitignore .heroku Procfile .profile.d README.md staticfiles
~ $ exit
exit
Run the command exit
to exit the Bash shell and terminate the dyno.
Define Config Vars
Heroku lets you externalize configuration by storing data such as encryption keys or external resource addresses in config vars.
At runtime, we expose config vars as environment variables to the application.
Edit hello/views.py
. At the beginning of the file, add a line to import the os
module:
import os
from django.http import HttpResponse
Now modify the index
method so that it repeats an action depending on the value of the TIMES
environment variable:
def index(request):
times = int(os.environ.get('TIMES', 3))
return HttpResponse('Hello! ' * times)
The heroku local
command automatically sets up the environment based on the contents of the .env
file in your local directory. In the top-level directory of your sample project, there’s already a .env
file that contains:
TIMES=2
Run the app with heroku local --port 5006
and visit http://localhost:5006 to see “Hello!” twice.
To set the config var on Heroku, execute this command:
$ heroku config:set TIMES=2
View the app’s config vars using heroku config
:
$ heroku config
=== serene-caverns-82714 Config Vars
PAPERTRAIL_API_TOKEN: <SECRET_TOKEN>
TIMES: 2
To see this change in action, deploy your changed application to Heroku.
Provision and Use a Database
The add-on marketplace has a large number of data stores, from Redis and MongoDB providers, to Postgres and MySQL.
An essential-0
Postgres size costs $5 a month, prorated to the minute. At the end of this tutorial, we prompt you to delete your database to minimize costs.
To provision an essential-0
Heroku Postgres add-on, use the addons:create
command:
$ heroku addons:create heroku-postgresql:essential-0
Creating heroku-postgresql:essential-0 on ⬢ serene-caverns-82714... ~$0.007/hour (max $5/month)
Database should be available soon
postgresql-deep-45610 is being created in the background. The app will restart when complete...
Use heroku addons:info postgresql-deep-45610 to check creation progress
Use heroku addons:docs heroku-postgresql to view documentation
You can find out a more about the database provisioned for your app using the addons
command in the CLI:
$ heroku addons
Add-on Plan Price Max price State
───────────────────────────────────────── ─────────── ──────────── ───────── ────────
heroku-postgresql (postgresql-deep-45610) essential-0 ~$0.007/hour $5/month creating
└─ as DATABASE
...
Listing the config vars for your app displays the URL that your app uses to connect to the database, DATABASE_URL
:
$ heroku config
=== serene-caverns-82714 Config Vars
DATABASE_URL: postgres://ub3r5i9vnl3fnm:<PASSWORD>@c5p86clmevrg5s.cluster-czrs8kj4isg7.us-east-1.rds.amazonaws.com:5432/d10gkj42hdl30i
...
Heroku also provides a pg
command that shows a lot more information:
$ heroku pg
=== DATABASE_URL
Plan: essential-0
Status: Available
Connections: 0/20
PG Version: 16.2
Created: 2024-08-09 09:55
Data Size: 7.57 MB / 1 GB (0.74%) (In compliance)
Tables: 0/4000 (In compliance)
Fork/Follow: Unsupported
Rollback: Unsupported
Continuous Protection: Off
Add-on: postgresql-deep-45610
This info shows an essential-0
database running Postgres v16.2 with no tables.
The example app you deployed already has database functionality, however, you must make two small changes to enable it.
First, uncomment the two psycopg
lines at the end of the requirements.txt
file:
psycopg[c]; sys_platform == "linux"
psycopg[binary]; sys_platform != "linux"
These lines ensure that the Postgres database adapter package installs during the build.
Next, uncomment the release
process line at the end of the Procfile
file:
release: ./manage.py migrate --no-input
This release
process entry enables the Heroku Release Phase feature, and uses it to run any Django database migrations whenever the app deploys.
Deploy your changed application to Heroku using the same deployment process as before. You can see Django’s database migrations run after the build:
remote: Running release command...
remote:
remote: Operations to perform:
remote: Apply all migrations: auth, contenttypes, hello, sessions
remote: Running migrations:
remote: Applying contenttypes.0001_initial... OK
remote: Applying contenttypes.0002_remove_content_type_name... OK
remote: Applying auth.0001_initial... OK
remote: Applying auth.0002_alter_permission_name_max_length... OK
remote: Applying auth.0003_alter_user_email_max_length... OK
remote: Applying auth.0004_alter_user_username_opts... OK
remote: Applying auth.0005_alter_user_last_login_null... OK
remote: Applying auth.0006_require_contenttypes_0002... OK
remote: Applying auth.0007_alter_validators_add_error_messages... OK
remote: Applying auth.0008_alter_user_username_max_length... OK
remote: Applying auth.0009_alter_user_last_name_max_length... OK
remote: Applying auth.0010_alter_group_name_max_length... OK
remote: Applying auth.0011_update_proxy_permissions... OK
remote: Applying auth.0012_alter_user_first_name_max_length... OK
remote: Applying hello.0001_initial... OK
remote: Applying sessions.0001_initial... OK
remote: Waiting for release.... done.
If the build fails with a settings.DATABASES is improperly configured
error, check that you provisioned the database add-on before deploying.
Visit the database demonstration page by visiting your app’s URL and appending /db
. For example, if your app was deployed to https://serene-caverns-82714.herokuapp.com/
then visit https://serene-caverns-82714.herokuapp.com/db
.
Access the /db
route again to see a simple page update every time you access it:
Page View Report
Aug. 9, 2024, 10:07 a.m.
Aug. 9, 2024, 10:08 a.m.
The code to access the database is straightforward. It uses a simple Django model called Greetings
that you can find in hello/models.py
.
Whenever you visit the /db
route of your app, the following method in the hello/views.py
file invokes and creates a greeting. It then renders all the existing greetings:
def db(request):
greeting = Greeting()
greeting.save()
greetings = Greeting.objects.all()
return render(request, 'db.html', {'greetings': greetings})
If you have Postgres installed locally, use the heroku pg:psql
command to connect to the remote database and see all the rows:
$ heroku pg:psql
--> Connecting to postgresql-deep-45610
...
Type "help" for help.
serene-caverns-82714::DATABASE=>
Read more about Heroku PostgreSQL.
You can use a similar technique to install MongoDB or Redis add-ons.
Next Steps
You now know how to deploy an app, change its configuration, view logs, scale, and attach add-ons.
Here’s some recommended reading:
- Read How Heroku Works for a technical overview of the concepts you encounter while writing, configuring, deploying, and running applications.
- To deploy an existing Python or Django app on Heroku, read Deploying Python and Django Apps on Heroku.
- To learn more about developing and deploying Python applications, visit the Python category.
Remember to delete your example app, and database as soon as you’re done with the tutorial, to control costs.
Delete Your App and Add-ons
Remove the app and database from your account. We only charge you for the resources you used.
This action removes your add-on and any data saved in the database.
$ heroku addons:destroy heroku-postgresql
This action permanently deletes your application
$ heroku apps:destroy
You can confirm that your add-on and app are gone with these commands:
$ heroku addons --all
$ heroku apps --all