Deploying Django Application on cPanel: A Comprehensive Tutorial
- Introduction
- Features
- General procedure for deploying a Django application
- Deployment Methods
- Supported Platforms
- WSGI and ASGI Interfaces
- Conclusion
- How to Deploy a Django Application on cPanel: Step-by-Step Tutorial
- Concepts
- References
Introduction
Django is a web framework that simplifies the development of web applications. It is a highly extensible framework that is ideal for building complex web applications. Django has a built-in web server, supports multiple databases, and provides a modular architecture.
Features
It also provides a number of features, including:
- A robust security model
- A flexible and extensible architecture
- A large and active community
General procedure for deploying a Django application
Deploying a Django application involves several key steps, from preparation to going live. This general procedure is designed to cover most deployment scenarios:
1. Preparation
- Requirements File: Ensure you have a
requirements.txt
file listing all your project dependencies. Generate it usingpip freeze > requirements.txt
if necessary. - Settings Configuration: Split your settings into base (common settings), development (for local development), and production (for deployment) settings. Ensure sensitive information is not hard-coded but instead is pulled from environment variables or a secure source.
- Static and Media Files: Configure your static files (CSS, JavaScript) and media files (uploads) settings properly for production.
2. Choose a Hosting Service
- Decide on a hosting service that supports Python and Django. Popular options include Heroku, AWS (Elastic Beanstalk or EC2), DigitalOcean, and Google Cloud Platform.
3. Set Up Your Server
- If not using a PaaS provider like Heroku, set up your server environment. This may involve installing Nginx or Apache for serving static files, and Gunicorn or uWSGI as the WSGI HTTP server to serve your Django app.
4. Database Configuration
- Configure your production database. Django supports several databases out of the box, including PostgreSQL, MySQL, and SQLite. For production, PostgreSQL or MySQL is recommended.
- Run
python manage.py migrate
to apply migrations to your production database.
5. Static and Media Files
- Collect static files using
python manage.py collectstatic
. This gathers all your static files in the directory specified bySTATIC_ROOT
. - Ensure your production environment has a place to store and serve media files uploaded by users.
6. Security Settings
- Enable
DEBUG = False
in your production settings. - Use Django’s
SECURE_SSL_REDIRECT
andCSRF_COOKIE_SECURE
settings to enforce HTTPS and secure cookies. - Update your
ALLOWED_HOSTS
with the domain names your app will be served from.
7. Deploy Your Code
- For PaaS (e.g., Heroku), follow the platform’s specific deployment process, often involving Git for pushing your code.
- For IaaS (e.g., AWS EC2), you might use SSH to upload your code and dependencies, then start your application server (e.g., Gunicorn) and configure your web server (e.g., Nginx) to proxy to your app.
8. Configure DNS
- Update your DNS settings to point your domain to your hosted application.
9. Monitor and Scale
- Monitor your application’s performance and error logs.
- Adjust resources and scale your app as needed based on traffic and usage patterns.
10. Continuous Integration/Continuous Deployment (CI/CD)
- Optionally, set up CI/CD pipelines for automated testing and deployment using tools like GitHub Actions, GitLab CI/CD, or Jenkins.
This procedure outlines a broad overview; specific steps may vary based on your hosting environment and other technical choices. Always refer to the official Django documentation and your hosting provider’s guidelines for the most accurate and secure deployment practices.
Deployment Methods
There are several ways to deploy a Django application:
- Using a web hosting service: This is the simplest option, where the hosting provider takes care of all the details of deploying and maintaining your application.
- Using a PaaS (Platform as a Service): A PaaS provides a more managed environment for deploying your application, including features such as automatic scaling and load balancing.
- Deploying on your own servers: This gives you the most control over your application’s environment but requires the most maintenance and expertise.
Supported Platforms
Django can be deployed on several platforms, including:
- Linux
- macOS
- Windows
- AWS
- Azure
- Google Cloud Platform.
WSGI and ASGI Interfaces
Django supports two interfaces, WSGI and ASGI, for communicating with web servers:
- WSGI (Web Server Gateway Interface): It is a standard interface that allows web servers to communicate with Python applications. Django supports the WSGI interface by providing a WSGI application object. Django uses WSGI to communicate with the Gunicorn web server, which is the default web server that is installed with Django. It is a synchronous interface, which means that the web server waits for the Python application to finish processing a request before sending the response.
- ASGI (Asynchronous Server Gateway Interface): It is a newer standard interface that is designed to be more efficient than WSGI. It is an asynchronous interface, which means that the web server can continue to process requests while the Python application is still processing a previous request. Django supports the ASGI interface by providing an ASGI application object. Asynchronous applications are able to handle multiple requests at the same time, which can improve the performance of your application. If you are using an asynchronous Python framework, such as Twisted or Tornado, you should use the ASGI interface to deploy your Django application. Django supports ASGI through the asgiref library.
Conclusion
Django is a powerful and flexible web framework that is ideal for building complex web applications. It provides several deployment options, including using a web hosting service, PaaS, or your own servers. You can choose the deployment method that best suits your team’s needs and requirements. Django supports two interfaces, WSGI and ASGI, for communicating with web servers. Redeploying a Django app on cPanel involves removing the existing app and creating a new app with the updated settings.
How to Deploy a Django Application on cPanel: Step-by-Step Tutorial
- Go to your Django project folder
- Within the folder you should find two folders, one is your environment and the other is your main project folder
- Zip your principal project folder i.e django_test
- Now login to your cPanel account, and navigate to the cPanel File Manager
- You can upload the zipped folder here by clicking on the “Upload” button. As you can see django_test.zip has been uploaded.
- Right-click on the zip file and extract it.
- Click on the project folder on the left-hand side panel and you will see the folder(myproject) within the main principal project folder(django_test). You can later delete the myenv folder after uploading as we will set up the environment for our project in cPanel itself.
- Check whether all the project directories have been uploaded properly.
- Navigate to cPanel home page and scroll down to the “Software” section. Click on “Setup Python App”
- If the “Setup Python App” feature is not visible within your cPanel interface, I recommend reaching out to the IT department for assistance in configuring your cPanel to enable this feature.
- IT: it-help@mtu.edu
- If the “Setup Python App” feature is not visible within your cPanel interface, I recommend reaching out to the IT department for assistance in configuring your cPanel to enable this feature.
- Click on “Create Application” button. As you can see I have already created an application.
- This is what you’ll see after you click on the button. Start filling in the required fields.
- Follow these steps:
- Select the appropriate Python version.
- Application root is basically your root-folder/project-folder. In this case django_test/myproject
- You can have multiple domains. Select the one you require for Application URL.
- You can leave the Application startup file and Application Entry point blank. It will be automatically generated.
- If you experience any problems like say the app crashes or encounter bugs or issues in deployment, we can refer to the log file.
- As you can see the virtual environment has been automatically generated for us.
Before proceeding, we need to understand some concepts:
Django Deployment with WSGI
When deploying a Django application using the WSGI standard, the application server interacts with the code using an application callable, which is typically called ‘application’ and is provided as an object in a Python module that can be accessed by the server. Django utilizes WSGI as its primary deployment platform. WSGI is a widely accepted Python standard for web servers and applications.
WSGI vs ASGI
At present, Django provides two options for communicating between web servers and applications, namely WSGI (Web Server Gateway Interface) and ASGI (Asynchronous Server Gateway Interface). WSGI is a widely adopted Python standard for this purpose, but it only works with synchronous code. In contrast, ASGI is a new standard that enables the use of asynchronous Python features and will support the development of asynchronous Django features.
WSGI Configuration
When you use Django’s startproject management command, it creates a basic WSGI configuration for your project. You can then make any necessary adjustments to suit your project’s specific requirements. This configuration can be used by any WSGI-compliant application server to run your Django application. By default, Django sets up a minimal WSGI configuration that can be further customized by the user. The WSGI interface allows Django to seamlessly communicate with web servers, making it a preferred option for deployment.
The Application Object
The application object is the entry point for a Django application running under WSGI. When a Django project is created using the startproject command, it generates a file called ‘wsgi.py‘, which contains the application callable that can be used in both development and production WSGI deployments. The path to the application callable is obtained by WSGI servers from their configuration, and Django’s built-in server reads it from the WSGI_APPLICATION setting. By default, this setting is ‘<project_name>.wsgi.application’, which points to the application callable in the ‘wsgi.py‘ file.
For example, suppose we have a Django project named ‘myproject‘ with an app named ‘myapp‘. We can use the ‘wsgi.py‘ file generated by the startproject command to specify the application callable. In this file, we can define our application object like this:
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
application = get_wsgi_application()
Here, we import the ‘get_wsgi_application’ function from Django’s ‘core.wsgi’ module, and set the ‘DJANGO_SETTINGS_MODULE’ environment variable to point to our project’s settings module. We then define our application object as the result of calling ‘get_wsgi_application()’. The WSGI server can then use this ‘application’ object to interact with our Django application.
Configuring the Settings Module
When your application is loaded by the WSGI server, Django imports the settings module which defines your entire application. The ‘DJANGO_SETTINGS_MODULE’ environment variable is used by Django to locate the appropriate settings module. This variable must contain the dotted path to the settings module. You can use different values for development and production depending on how you organize your settings. If this variable is not set, the default wsgi.py sets it to ‘mysite.settings’, where ‘mysite’ is the name of your project. This is how ‘runserver’ discovers the default settings file by default.
For example, if you have a Django project named “myproject” with the settings file in a subdirectory called “config”, the ‘DJANGO_SETTINGS_MODULE’ environment variable can be set to ‘”myproject.config.settings“’ to load the correct settings file. Similarly, if you have separate settings for development and production, you can set the environment variable to “myproject.config.settings.development” or “myproject.config.settings.production” depending on the environment. This allows you to keep your settings organized and separate for different environments.
Django Environment Detection
This Python snippet below detects whether the Django web application is running in a production or development environment. It relies on the Django settings module to determine the environment based on the value of the DEBUG setting.
from django.conf import settings
def is_production():
"""
Checks if the environment is production.
Returns:
True if the environment is production, False otherwise.
"""
return settings.DEBUG is False
def is_development():
"""
Checks if the environment is development.
Returns:
True if the environment is development, False otherwise.
"""
return settings.DEBUG is True
if is_production():
what_is_the_env = 'DEV'
print(what_is_the_env)
else:
what_is_the_env = 'PROD'
print(what_is_the_env)
Functions
is_production(): This function checks if the environment is set to production.
Returns: True if the environment is production. False otherwise.
is_development(): This function checks if the environment is set to development.
Returns: True if the environment is development. False otherwise.
Example Usage
You can use these functions to conditionally execute code depending on the detected environment.
if is_production():
what_is_the_env = 'DEV'
print(what_is_the_env)
else:
what_is_the_env = 'PROD'
print(what_is_the_env)
In this example, it will print “PROD” if the Django application is running in a production environment (DEBUG is False) and “DEV” if it’s running in a development environment (DEBUG is True).
By utilizing these functions, you can ensure that your Django application behaves differently based on whether it’s in a production or development environment, which is crucial for tasks such as debugging, error handling, and configuration management.
- Now head over to cPanel. Open the ‘passenger_wsgi.py’ file by clicking on Edit. ‘passenger_wsgi.py’ file is created by cPanel and is your Application startup file.
- This(Figure below the code snippet) is the code you will find in the passenger_wsgi.py file. We need to make some changes to the code. Comment out the ‘application’ function as shown below. Add the following line.
from myproject.wsgi import application
- ‘myproject.wsgi’ is basically calling the ‘wsgi.py’ file within the directory. The directory also has our application’s ‘settings.py’ file.
- If you Edit/View the ‘wsgi.py‘ file, you will see an instance of our application. This instance is what your are importing in passenger_wsgi.py
- After navigating to Setup Python App and click on the edit button as shown below.
- As you can see we have the following. Application URL and Application startup file have been automatically generated.
- Now it is time to install Django on our server. Copy the following environment path.
- Go back to cPanel’s home page and you should see the Advanced section as you scroll down. Click on ‘Terminal’
- Copy and paste the path on the terminal and then press Enter. Once you are inside the virtual environment, then execute the command: ‘pip install Django’. You can install all the required libraries with specific versions in your virtual environment.
- You can also install the required libraries by adding the projects ‘requirements.txt’ file below and clicking on ‘Run Pip Install’ or entering the path to the script file and clicking on ‘Run Script’. This will install all required libraries and tools on the server.
- Now you have to restart the application before loading it on the browser. Navigate to Setup Python App and restart the application.
- Edit/View your ‘settings.py’ file and make sure you have added the application URL in the ALLOWED_HOSTS list. Also, according to the requirements check whether DEBUG has to be set to True or False
- Edit/View the following files by navigating to the project’s application folder.
- In the ‘urls.py’ file you will find a list of all your paths/urls in the ‘urlpatterns’ list.
- In the ‘views.py’ file you will find all the views and their associated methods of your application.
- You can test the application by navigating to Setup Python App and clicking on the application URL as shown below.
- Result:
References
- “Deploying Django Web Application using Cpanel. | by Python Zimbabwe Open Source.” 2020. Medium. | https://medium.com/@pyzimos/deploying-django-web-application-using-cpanel-6687b8057439
- “Deploying/Hosting a Django Website on cPanel with Git Version Control.” 2021. Naitik Parmar. | https://parmarnaitik0909.medium.com/deploying-hosting-a-django-website-on-cpanel-with-git-version-control-6e8dce70a316
- “Deploying your Python/Django app on cPanel using a git repository – Webhostpython.” 2020.Webhostpython. | https://blog.webhostpython.com/2020/10/14/deploying-your-python-django-app-on-cpanel-using-a-git-repository/.
- “Django Deploy to cPanel: Passengerfile.json’ for reading: Permission denied (errno=13).” 2021.Stack Overflow. | https://stackoverflow.com/questions/69145378/django-deploy-to-cpanel-passengerfile-json-for-reading-permission-denied-err.
- Guide, step. n.d. “Charlie Eleanor Awbery.” Charlie Eleanor Awbery. Accessed April 10, 2023. | https://charlieawbery.com/deploying_django/4/.
- Gyford, Phil, and Phil Gyford’s. 2022. “Hosting a Django site on cPanel.” Phil Gyford’s website. | https://www.gyford.com/phil/writing/2022/05/24/hosting-django-cpanel/.
- “How do I deploy a Django website with cPanel?” 2020. Stack Overflow. | https://stackoverflow.com/questions/59801135/how-do-i-deploy-a-django-website-with-cpanel?rq=1.
- “How to deploy with WSGI.” n.d. Django documentation | https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/.
- “How to use the Python Selector in cPanel.” n.d. A2 Hosting | https://www.a2hosting.com/kb/cpanel/cpanel-software/using-the-python-selector/.
- “Setup Python WSGI apps on cPanel (Flask/Django).” 2020. DevDungeon. | https://www.devdungeon.com/content/setup-python-wsgi-apps-cpanel-flaskdjango#toc-8.
- Sims, Tonya. 2021. “How Python’s WSGI vs. ASGI is Like Baking a Cake | Vonage API Developer.” Vonage Developer. | https://developer.vonage.com/en/blog/how-wsgi-vs-asgi-is-like-baking-a-cake.
- Stephen, Nganga. 2022. “How to publish/deploy Django website in Cpanel ‣ ngangasn.com.” Nganga Stephen | Web Developer \ https://ngangasn.com/deploy-django-on-shared-hosting-ultimate-guide-to-hosting-django-on-cpanel/#setup-domain.
- Umer, Hafiz M. 2019. “Deploy Django app on Shared Hosting using CPanel.” Umer Softwares Blog. | https://blog.umersoftwares.com/2019/09/django-shared-hosting.html.