Heroku is a popular cloud-based Platform-as-a-Service (PaaS) that provides developers with an easy way to deploy, manage, and scale their applications. In this blog post, we will explore how to deploy a Django application on Heroku.
Prerequisites
Before we begin, you will need the following:
- A basic understanding of Django development
- A Heroku account (sign up at https://www.heroku.com)
- The Heroku CLI (command-line interface) installed on your machine
Step 1: Setup
- Create a new directory for your Django project.
- Initialize a new Git repository by running
git init
. - Create a new virtual environment by running
python -m venv venv
. - Activate the virtual environment by running
source venv/bin/activate
on macOS/Linux orvenv\Scripts\activate
on Windows. - Install Django and other dependencies by running
pip install django
.
Step 2: Create a Django App
- Create a new Django app by running
django-admin startproject myproject
(replacemyproject
with the name of your project). - Change to the project directory by running
cd myproject
. - Create a new Django app within the project by running
python manage.py startapp myapp
(replacemyapp
with the name of your app).
Step 3: Configure the Django App
- Open the
settings.py
file in your project folder. - Update the
DATABASES
settings to use a Heroku Postgres database (you can provision it through the Heroku dashboard). - Set the
ALLOWED_HOSTS
setting to['*']
to allow Heroku to access your app. - Install the
gunicorn
package by runningpip install gunicorn
. - Create a new file called
Procfile
in the project root directory with the following content:web: gunicorn myproject.wsgi
. - Create a new file called
runtime.txt
in the project root directory and specify the Python version you are using (e.g.,python-3.9.6
).
Step 4: Initialize Git and Deploy to Heroku
- Run
git add .
to add all the files to your Git repository. - Commit the changes by running
git commit -m "Initial commit"
. - Login to Heroku from the command line by running
heroku login
. - Create a new Heroku app by running
heroku create
. - Set the Heroku remote as the Git repository's remote by running
heroku git:remote -a your-app-name
(replaceyour-app-name
with the name of your Heroku app). - Push your code to the Heroku remote by running
git push heroku main
. - Run the migrations on the Heroku server by running
heroku run python manage.py migrate
. - Open your app in the browser by running
heroku open
.
Conclusion
By following the above steps, you should now have your Django application deployed and running on Heroku. You can continue to add features and make changes to your app and deploy them using the same Git workflow. Heroku also provides additional tools and services to manage and scale your application as needed. Happy coding!
本文来自极简博客,作者:技术解码器,转载请注明原文链接:Deploying Django Applications: Heroku