DEV Community

chryzcode
chryzcode

Posted on

Best Practices For Deploying Django Applications(Production Environment and Hosting)

Introduction

Hosting and deploying projects is a core and important phase of software and web development. What's the joy, happiness and pride in building a project or product and not being able to share it with the world? How can constructive feedback that promotes improvement be gotten? This has been an issue or problem faced by many developers (myself included), especially newbies.

Building a project in a local environment is different from that of a production environment because of a lot of configurations involved which will shared in this article for Django projects using a PostgreSQL database on the Heroku platform.

Why PostgreSQL Database and Heroku?

You might be wondering why a PostgreSQL database and Heroku for deploying and hosting. If you are curious about this continue reading and if not you can skip it.

PostgreSQL Database

The default database for a Django project is SQLite, it is efficient to use in a local environment but not a production environment. These are a few of the reasons that justify the statement aforementioned:

  • The bandwidth of PostgreSQL is wider and stronger.

  • There are lots of hosting platforms that offer PostgreSQL database services.

  • The PostgreSQL database file does not need to be in the project folder or directory before functioning, unlike SQLite. (The Host of the database made it possible).

    • Databases should not be exposed/ revealed publicly(i.e. you can not push your database to a version control system. It needs to be hidden and this makes an SQLite database unavailable for deployment.
  • PostgreSQL is versatile. It can be used in both a local and production environment(Synchronization and unity of data)

There are other options when it comes to the choice of database like Oracle, MySQL, MariaDB etc. but we will not be heading in that direction in this article.

Heroku

There is a need for a hosting and deploying platform and there are quite a variety of them like Render, Fly, BlueHost, AWS, Google Cloud, Railway etc. Below are a few reasons why I chose Heroku despite their change of billing policies which has been for a while now:

  • The configuration process is not difficult and frustrating.

  • Heroku has 3 deployment methods, deploying using the Heroku CLI, GitHub(through the website) and Container Registry. In this article, we will be using GitHub which is the easiest of all.

  • Creation Heroku applications are free but to use addons(resources), like Heroku PostgreSQL you need to add a debit/ credit card and the plans are fair.

Getting started

Prerequisites and Requirements

Here are the prerequisites and requirements to get started deploying your Django application on Heroku:

Configuring settings for static files

What are static files?

They are files that can not be converted, modified, changed or processed when an application is running. Examples are Javascript and CSS files, images etc. To make Heroku serve these files as they ought to be, the following steps need to be taken.

  • Install Whitenoise

    With a couple of lines of config, WhiteNoise allows your web app to serve static files, making it a self-contained unit that can be deployed anywhere without relying on nginx, Amazon S3 or any other external service. (Especially useful on Heroku, OpenShift and other PaaS providers.)#make sure.

    #make sure your project virtual environment is activated
    pipenv install whitenoise
    
  • Configuring whitenoise in settings.py file

    #setting the directory and root of the staticfiles for accesibility
    STATICFILES_DIRS = [os.path.join(BASE_DIR, 'staticfiles')]
    
    #whitenoise configuration
    STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
    

Setting Heroku and project up for deployment

To deploy the application, both the Heroku CLI and the website will be used. To verify if you have Heroku installed properly, use the command below;

#check for the version of Heroku installed
heroku -v

#install django-heroku package in your project
pipenv install django_heroku

#install gunicorn
pipenv install gunicorn

# to use postgresql in our django hosted project
pipenv install psycopg2-binary
Enter fullscreen mode Exit fullscreen mode
  • Create a Procfile in your project

    It is a file that specifies the commands that are executed by a Heroku app on startup. Make sure it is located at the base path of the project. Insert the code below into the Procfile

    # it connects to the wsgi file of the project
    web: gunicorn my_project.wsgi --log-file -
    
  • Create an application on Heroku
    Image description

  • Create a Postgres Database on Heroku

    While on the newly created application click on the Resources tab search and click Heroku Postgres on Add-ons search bar. Choose your desired plan and click on it after it has been created to see the database credentials details.

Image description

  • Install django-decouple

    It is a Python library aimed at making it easier for developers to separate their configuration settings from code

    pipenv install python_decouple
    
  • settings.py configuration

    #add this at the begining of settings.py file
    from decouple import config
    import django_heroku
    
    # update these
    SECRET_KEY = config('SECRET_KEY')
    
    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = config("DEBUG", default=False, cast=bool)
    
    # the last value is the url of the Heroku app, remove the https:/
    ALLOWED_HOSTS = ["127.0.0.1", "localhost", "my-test-django-project-9a47545252ae.herokuapp.com"]
    
    #update the database from sqlite to postgres
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            "NAME": config("DB_NAME"),
            "USER": config("DB_USER"),
            "PASSWORD": config("DB_PASSWORD"),
            'HOST': config("HOST"),
            'POST': '5432',
        }
    }
    
    # Activate Django_heroku.
    django_heroku.settings(locals())
    
  • Create .env and .gitignore file

    A .env file is where the secrets and sensitive keys of a project are kept to prevent exposure especially when pushed to GitHub, GitLab etc. Link to a git ignore file

    See to it that both files are located at the base path of the project.

    DEBUG=True
    SECRET_KEY=jferjrjtgotuggfuopfddl #just a sample 
    DB_NAME=#database name
    DB_USER=#user
    DB_PASSWORD=#password
    HOST=#the host
    
  • Delete sqlite database db.sqlite3 and migrate

    python manage.py migrate
    
  • Add .env details

    Go to the application on the Heroku website and click on settings tab and the Reveal Config Vars button to add all the details in the .env files.

Image description

  • Deployment

    As said earlier, we will be deploying using the GitHub method on Heroku, so make sure to push your code to GitHub. Navigate to the deploy tab to connect the application to the GitHub repository. Then, scroll down and click the deploy branch button to start the deployment process.

Image description

You should have your hosted project running live on Heroku. Hope you enjoyed the hands-on tutorial-based-article

Top comments (0)