django

How to deploy a Django application on Heroku?

ProgrammingForNoobs

Following are the steps to deploy the Django application on Heroku.

  • Create a GitHub repository for your project. We are going to connect this repository with Heroku.
  • Login to your Heroku account.
  • Click on Create a new app.
Create new app
Create new app
  • Give your app name and select the region.
Select name and region
Select name and region
  • Click on connect to Github. 
  • Search your repository name and click on connect.
  • Now select your project locally. Open in your code editor. I am using Visual Studio Code.
  • Create one new file with the name Procfile.
Open Project
Open Project
  • Inside the Procfile. Give the following command line.
web: gunicorn project.wsgi
Note - Replace the project name with the actual project name.
Note - Replace the project name with the actual project name.
  • Now we need to install gunicorn and django-heroku using pip. Use following the commands.
pip install gunicorn django-heroku
  • Open setting.py and importthe django_heroku and place this piece of code at the bottom of the file. 
import django_heroku

# Copy/Paste at the bottom
django_heroku.settings(locals()) 
  • Also, You need to provide the path for the static files. For that, you can use the following code.
# For locating your base directory.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'

# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

Note - Heroku automatically runs the command python manage.py collectstatic. We don't need to configure anything extra for that.

  • Now you need to push your code on Github.
  • Now you can deploy your branch/code. Click on Deploy Branch.
  • If you have configured everything correctly then, then you will see the following output.
Deployed
Deployed
  • Now, You can visit your admin. 
Admin
Admin
  • Wait, But we have not created any admin login and password.
  • You can use Heroku CLI for that.

Note - You must need login with your Heroku CLI, then you can use the following command.

  • First, we need to run migrations. 
heroku run python manage.py migrate -a 

Replace app_name with the app name that you have entered during the creation of the Heroku project.

  • Now you can use the following command for creating a superuser.
heroku run python manage.py createsuperuser -a <app_name>

Comments