DEV Community

Cover image for How to Deploy your Django Web App and connect a MySQL Database in cPanel
Nick
Nick

Posted on

How to Deploy your Django Web App and connect a MySQL Database in cPanel

Introduction

With many businesses going online, there is an increasing demand for web hosting services. Hosting services provide a platform where web developers can store web application files in a production environment.

Several hosting services exist in the market. The services cater to a range of client needs, which includes the volume of traffic a web service is expected to receive, security needs and performance.

Hosting services such as Digital Ocean are suitable when a web application is expected to receive huge traffic. However, such hosting sites are usually cost-prohibitive. In contrast, hosting services such as cPanel can efficiently host sites that handle medium to low traffic at lower costs. Moreover, cPanel is a convenient to-go service for practice projects. This article guides on how to host a Python Django project in cPanel.

Prerequisites

  • An existing Django project
  • A cPanel account with a domain name
  • A zipped file of your website (Should be a .zip extension)

Meeting the Prerequisites

If you do not have an existing Django project, use one here. For a cPanel account and domain set up, check this out. Now that you are ready to go with a Django project and a cPanel account, create a zipped file of your website like this:

Linux

  1. Navigate to the directory that hosts your project's folder
  2. Type the command below. Remember to replace archive.zip and your_project_folder with actual names. bash zip -r archive.zip your_project_folder

Windows

  1. Navigate to your project's folder location.
  2. Right click on the folder and select Add to archive. A .zip file will be created.

Upload your Files

  1. Log in to cPanel using the username and password you set with the hosting provider
  2. Navigate to the File Manager section on the cPanel dashboard. Click and select Public_html under File Manager.

    File manager section

    Note: This is only applicable if you are uploading the web app for the main domain and not the add-on domain or subdomain as they are located in a different folder within the file manager.

  3. Click on Upload then Select File. You will be prompted to select a file from you PC.

    Uploads option

  4. Select the zipped file from your PC and hit upload. Alternatively you could drag and drop the .zip file to cPanel. Once the file finishes uploading, click on go back to return to the Public_html directory.

  5. Locate your zipped file and right click on it, then select extract to extract subfolders and files within it.

    Extract file option

Now your files are ready

Set up a MySQL Database

Note: You need to perform this step before you set up your Django app. To set up a MySQL database:

  1. Locate the Databases section on the cPanel dashboard.
  2. Select MySQL Databases.

    MySQL Database section

  3. Create a database with a suitable name in the provided Create New Database field.

  4. Input user credentials, a username and password, in the Create New User field to create a new user. Copy the password somewhere as you will need it to configure the database.

  5. In the User Privileges section, check All Privileges

  6. Confirm that the database has been created by clicking on the phpMyAdmin option under Databases section.

  7. Configure a MySQL database in your settings.py file.
    In development, you most likely have been using an SQLite database. Since we have switched to a MySQL database, you need to configure the new database settings.

    Locate the DATABASES section in your project's settings.py file and replace the existing database settings with the code below. Remember to replace the NAME (database name), USER, and PASSWORD fields with actual values:

    #settings.py
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'mysql_db_name',
            'HOST': 'localhost',
            'PORT': 3306,
            'USER': 'my_sql_user',
            'PASSWORD': 'password',
        }
    }
    
  8. Save and close the file.

Your database is now configured.

Set up Your Django App

Create Your App

  1. Locate the Software options in the cPanel Dashboard
  2. Click on Setup Python App

    cPanel software section

  3. Select CREATE APPLICATION to begin setting up your Python app.

  4. Select a Python version. The latest is recommended.

  5. Input the root directory of your project under the Application root field. For instance, if your application root folder is called Django-project and you uploaded it to Public_html, your application root becomes Public_html/Django-project

  6. Select a domain name for your application. The main domain is selected by default.

  7. Leave the Application startup file and Application Entry point fields empty. The build process will fill them appropriately.

  8. Hit the CREATE button in the top right bar to create your application.
    Notice that the build process has filled the two empty fields. We will need the passenger_wsgi.py file in a moment.

  9. Edit the passenger_wsgi.py file.

    When you created your web app, the build process generated a file named passenger_wsgi.py and stored it in the root directory of your project. You need to edit this file so that the production server can serve your application. Right click on the file and select the edit option. Once the file is opened, delete all contents in the file except the two import statements at the top. Next, add the following line below the imports:

# passenger_wsgi.py
import os
import sys

from wsgi_directory.wsgi import application
Enter fullscreen mode Exit fullscreen mode

The line imports your application object from the wsgi.py file located in the same directory as your settings.py. Remember to replace wsgi_directory with the actual name of the directory. Next, save and close the file.

Your have created a basic application

Note: For subsequent steps, you might run into errors when installing dependencies and/or when running migrations. Such errors could, most likely, be a result of issues in your source code. You can inspect the stderr.log file for error details. This file was created together with your app, and is located in your project's root directory. Read the error log and fix any problems in your source code before you proceed.

Set up a Virtual Environment

Activate a Python virtual environment. This is necessary to store and separate your project's dependencies.

  • Note 1: A virtual environment link was generated when you created the application. It can be accessed at the top of the page.

Your app's virtual environment link

  • Note 2: You need to copy the link and paste it in a bash terminal provided by the hosting service. The terminal should be under Advanced section on the cPanel dashboard.
  • Note 3: Depending on your hosting plan, the terminal may not be available to you.

If you can access the terminal:

  1. Paste the virtual environment path into the terminal and press Enter. The process activates a virtual environment and changes into your project's root directory.
  2. Install project dependencies: python pip install -r requirements.txt
  3. Create the database schema and tables python python manage.py makemigrations python manage.py migrate

If you do not have access to a terminal:

  1. Select the Setup Python App option. You should see your app under WEB APPLICATIONS.
  2. Click on the edit icon under Actions and scroll down to Configuration files.

    Configurations section

  3. Enter the name of your dependencies file, in our case the requirements.txt file, in the field provided, and click the Add button.

  4. Click on Run Pip Install button, which will prompt you to select the requirements.txt file you just added.

    Wait for a few moments while the build process installs dependencies in your virtual environment. You should get a successfully installed pop-up message as soon as the process completes

  5. Enter the following commands, one at a time, in the Execute python scripts field and press the Run Script button. This step is crucial to create database schema and tables, based on your models.py file, in the database you set up earlier.

    manage.py makemigrations
    manage.py migrate
    

    Note: If you uploaded your files to Public_html and entered the commands exactly as above, it should work. However, if you uploaded your files to a different directory, you would need to specify the full path to the manage.py file. Additionally, if you have more than one project in the Public_html directory, you may need to specify the path to a specific manage.py file. This tutorial assumes only one manage.py file is available in Public_html directory.

  6. Set Your Environment Variables

    This step is crucial if you used any environment variables within your app. For instance, you might have used an environment variable as a place holder for the SECRET_KEY variable in your settings.py file.

cPanel Environmental Variables section

Conclusion

This tutorial provides a comprehensive guide to correctly hosting your project in cPanel. Hosting your Django web app with cPanel essentially involves three major steps:

Deploying your Python project to cPanel could be challenging for beginners. However, in this author's opinion, cPanel has a gentler learning curve compared to other hosting sites. The above guidelines have expounded on the steps above in detail, including providing information on potential pitfalls. Happy hosting!

Top comments (3)

Collapse
 
marioalexandreantunes profile image
Mario Antunes

Use it a lot, with github and actions to automate the deploys.
Great Post.

Collapse
 
haude419 profile image
haude419

can not build wheel error during
pip install mysqlclient?

Collapse
 
odhiambo profile image
Nick