how to deploy django app on heroku with mongodb
- Ensure you have the required dependencies installed:
pip install djongo dj-database-url
- Update your
requirements.txt
file:
djongo==1.3.5
dj-database-url==0.5.0
- Install Gunicorn:
pip install gunicorn
- Update your
requirements.txt
file:
gunicorn==20.1.0
- Create a Procfile in your project root:
echo "web: gunicorn your_project_name.wsgi" > Procfile
- Install Heroku CLI and login:
# Install Heroku CLI
npm install -g heroku
# Login to Heroku
heroku login
- Initialize a Git repository (if not already):
git init
git add .
git commit -m "Initial commit"
- Create a Heroku app:
heroku create your-app-name
- Set environment variables for your Django app:
heroku config:set DJANGO_SETTINGS_MODULE=your_project_name.settings
- Configure MongoDB connection in your settings.py:
import dj_database_url
DATABASES = {
'default': dj_database_url.config(default=os.environ.get('DATABASE_URL'))
}
- Update ALLOWED_HOSTS in settings.py:
ALLOWED_HOSTS = ['your-app-name.herokuapp.com', 'localhost']
- Migrate your database:
python manage.py makemigrations
python manage.py migrate
- Add your MongoDB URI to Heroku environment variables:
heroku config:set DATABASE_URL=<your-mongodb-uri>
- Add static files configuration:
import os
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
- Update your requirements.txt file:
whitenoise==5.3.0
- Update your middleware in settings.py:
MIDDLEWARE = [
# ...
'whitenoise.middleware.WhiteNoiseMiddleware',
# ...
]
- Collect static files:
python manage.py collectstatic
- Commit changes to Git:
git add .
git commit -m "Configuring for Heroku deployment"
- Push your code to Heroku:
git push heroku master
- Open your deployed app:
heroku open
That's it! Your Django app with MongoDB should now be deployed on Heroku.