DEV Community

Cover image for How to host a Django project on Heroku (for free)
O. AlQudah
O. AlQudah

Posted on

How to host a Django project on Heroku (for free)

This step-by-step beginner tutorial will teach you how to host your local Django project on Heroku for free. I haven't found many easy to follow tutorials on this topic so I decided to make my own after hosting many projects with the mentioned steps. Enjoy!

Steps

  • Create and activate a virtualenv, install dependancies.
python -m venv <env_name> # Windows python3 -m venv <env_name> # Other env\Scripts\activate # Windows source venv/bin/activate # Other 
Enter fullscreen mode Exit fullscreen mode
  • Initialize a git repository (git init)
  • Add a .gitignore file

Suggested gitignore for Django

  • Add the following to settings.py:
STATIC_ROOT = os.path.join(BASE_DIR, 'static') 
Enter fullscreen mode Exit fullscreen mode
python-3.10.1 
Enter fullscreen mode Exit fullscreen mode
  • Install gunicorn:
pip install gunicorn 
Enter fullscreen mode Exit fullscreen mode
  • Create Procfile and add the following:
web: gunicorn myproject.wsgi 
Enter fullscreen mode Exit fullscreen mode
  • Install django-on-heroku:
pip install django-on-heroku 
Enter fullscreen mode Exit fullscreen mode
  • Add the following to settings.py:
# Configure Django App for Heroku. import django_on_heroku django_on_heroku.settings(locals()) 
Enter fullscreen mode Exit fullscreen mode
  • Add requirements.txt by running:
pip freeze > requirements.txt 
Enter fullscreen mode Exit fullscreen mode
  • Commit your changes:
git add . git commit -m "Init commit" 
Enter fullscreen mode Exit fullscreen mode
  • Login to heroku from the command line:
heroku login 
Enter fullscreen mode Exit fullscreen mode
  • Create a new app:
heroku create app_name 
Enter fullscreen mode Exit fullscreen mode
  • Add your heroku app to ALLOWED_HOSTS:
ALLOWED_HOSTS = ['your_app_name.herokuapp.com', ...] 
Enter fullscreen mode Exit fullscreen mode
  • Commit your changes:
git add . git commit -m "Configure ALLOWED_HOSTS" 
Enter fullscreen mode Exit fullscreen mode
  • Push your changes to heroku branch:
git push heroku master # Or branch name 
Enter fullscreen mode Exit fullscreen mode
  • Migrate your database:
heroku run python manage.py migrate 
Enter fullscreen mode Exit fullscreen mode
  • Make sure you have DEBUG = False in your settings.py file.

Extras

  • Open your app online:
heroku open 
Enter fullscreen mode Exit fullscreen mode
  • Create admin account:
heroku run python manage.py createsuperuser 
Enter fullscreen mode Exit fullscreen mode
  • If you have static files, run:
heroku run python manage.py collectstatic 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)