How to Install Django on a Hosting Server: A Complete Step-by-Step Guide
Django is a high-level Python web framework designed to encourage rapid development and clean, pragmatic design. It remains one of the most popular choices for building scalable, secure, and maintainable web applications β from simple blogs to complex enterprise platforms. In this comprehensive guide, we'll walk you through every step required to install Django on a hosting server, from preparing your Linux environment to running your first project and preparing it for production.
Why Choose Django for Your Web Application?
Before diving into the installation process, it's worth understanding why Django continues to dominate the Python web development landscape:
- Batteries included: Django ships with built-in authentication, an admin panel, ORM, form handling, and security features out of the box.
- Scalability: Django powers high-traffic platforms like Instagram and Pinterest.
- Security-first design: Django protects against common vulnerabilities including SQL injection, XSS, CSRF, and clickjacking by default.
- Rapid development: Its convention-over-configuration philosophy lets developers ship features faster.
- Massive ecosystem: Thousands of reusable packages and a large community mean solutions to almost any problem already exist.
To get the most out of Django, you'll want a reliable server environment. A VPS Hosting plan gives you the root access, dedicated resources, and flexibility that Django applications demand.
Prerequisites
Before you begin the installation process, make sure you have the following in place:
- A hosting server running a Linux distribution (Ubuntu 20.04/22.04 or Debian are recommended)
- SSH access to the server with sudo privileges
- Python 3.8 or higher (Python 3.10+ recommended)
pip(Python's package manager) installed- Basic familiarity with the Linux command line
> Pro Tip: If you're running a production Django application, avoid shared hosting environments. A VPS Hosting plan or a Dedicated Server will give you the control and performance your application needs.
Step 1: Connect to Your Server via SSH
Open your terminal and establish an SSH connection to your hosting server:
ssh username@server_ipReplace username with your actual system username and server_ip with your server's public IP address. If you're using a custom SSH port or a key-based authentication file, adjust the command accordingly:
ssh -i /path/to/your/key.pem username@server_ipOnce connected, you'll have a command-line interface to your server where you can begin the setup process.
Step 2: Update Your System and Install Python & pip
Keeping your system packages up to date is a critical first step for both security and compatibility.
Update the Package Index
sudo apt update && sudo apt upgrade -yInstall Python 3 and pip
Most modern Ubuntu and Debian distributions ship with Python 3 pre-installed. Verify your Python version first:
python3 --versionIf Python 3 is not installed, or you need pip, install them with:
sudo apt install python3 python3-pip -yVerify the installations:
python3 --version
pip3 --versionYou should see version numbers confirming both tools are available.
Step 3: Set Up a Python Virtual Environment
Using a virtual environment is not just recommended β it is considered best practice for every Python project. Virtual environments isolate your project's dependencies from the system-wide Python installation and from other projects on the same server, preventing version conflicts and keeping your environment clean.
Install virtualenv
sudo pip3 install virtualenvAlternatively, you can use Python's built-in venv module (available in Python 3.3+):
sudo apt install python3-venv -yCreate Your Project Directory and Virtual Environment
Navigate to the directory where you want to host your project, or create a new one:
mkdir myproject
cd myprojectNow create the virtual environment inside your project directory:
virtualenv venvOr, using the built-in venv module:
python3 -m venv venvActivate the Virtual Environment
source venv/bin/activateOnce activated, your command prompt will change to show the virtual environment name, for example:
(venv) username@server:~/myproject$All pip install commands executed while the virtual environment is active will install packages only within this isolated environment. To deactivate it at any time, simply run:
deactivateStep 4: Install Django
With your virtual environment active, install Django using pip:
pip install djangoTo install a specific version of Django (recommended for production to ensure compatibility):
pip install django==4.2Verify the installation:
django-admin --versionYou should see the installed Django version number printed to the terminal.
Step 5: Create a New Django Project
Use Django's built-in django-admin command-line tool to scaffold a new project:
django-admin startproject myproject .> Note: The trailing dot (.) tells Django to create the project files in the current directory rather than creating a nested subdirectory. This is a cleaner structure for most deployments.
Your project directory will now contain the following structure:
myproject/
βββ manage.py
βββ myproject/
βββ __init__.py
βββ asgi.py
βββ settings.py
βββ urls.py
βββ wsgi.pymanage.pyβ A command-line utility for interacting with your Django project.settings.pyβ The central configuration file for your project.urls.pyβ The URL routing configuration.wsgi.py/asgi.pyβ Entry points for WSGI and ASGI-compatible web servers.
Step 6: Configure Database Settings
Open the settings.py file to configure your database connection:
nano myproject/settings.pyDefault: SQLite (Development Only)
By default, Django is configured to use SQLite, which is suitable for development and testing but not recommended for production:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}Production Option: PostgreSQL
PostgreSQL is the most commonly recommended database for Django in production. First, install the required packages:
sudo apt install postgresql postgresql-contrib libpq-dev -y
pip install psycopg2-binaryThen update the DATABASES setting in settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydatabase',
'USER': 'myuser',
'PASSWORD': 'mypassword',
'HOST': 'localhost',
'PORT': '5432',
}
}Production Option: MySQL / MariaDB
If you prefer MySQL or MariaDB, install the required adapter:
sudo apt install default-libmysqlclient-dev -y
pip install mysqlclientThen configure the DATABASES setting:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydatabase',
'USER': 'myuser',
'PASSWORD': 'mypassword',
'HOST': 'localhost',
'PORT': '3306',
}
}Configure ALLOWED_HOSTS
While in settings.py, also update the ALLOWED_HOSTS setting to include your server's IP address or domain name. This is required for Django to serve requests in non-debug mode:
ALLOWED_HOSTS = ['your_server_ip', 'yourdomain.com', 'www.yourdomain.com']Step 7: Apply Database Migrations
Django uses a migration system to manage database schema changes. Run the initial migrations to create all the necessary database tables:
python manage.py migrateYou'll see output listing each migration being applied. A successful migration looks like:
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
...Create a Superuser (Optional but Recommended)
Create an admin account to access Django's built-in admin interface:
python manage.py createsuperuserYou'll be prompted to enter a username, email address, and password.
Step 8: Run the Django Development Server
You can now start Django's built-in development server to verify your installation:
python manage.py runserver 0.0.0.0:8000This command binds the development server to all available network interfaces on port 8000. Open your web browser and navigate to:
http://your_server_ip:8000You should see the Django welcome page β a rocket ship with the message "The install worked successfully! Congratulations!"
To access the admin panel, navigate to:
http://your_server_ip:8000/admin> Important: Django's built-in development server is not suitable for production. It is single-threaded, not optimized for performance, and lacks security hardening. Always use a production-grade web server for live deployments.
Step 9: Prepare Django for Production (Recommended)
For production deployments, you need to configure a proper web server stack. The most common and recommended setup is Nginx + Gunicorn.
Install Gunicorn
With your virtual environment active:
pip install gunicornTest that Gunicorn can serve your application:
gunicorn --bind 0.0.0.0:8000 myproject.wsgiInstall and Configure Nginx
sudo apt install nginx -yCreate an Nginx server block configuration file:
sudo nano /etc/nginx/sites-available/myprojectAdd the following configuration:
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/username/myproject;
}
location / {
include proxy_params;
proxy_pass http://unix:/run/gunicorn.sock;
}
}Enable the configuration and restart Nginx:
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginxCollect Static Files
Update settings.py with the static files directory:
STATIC_ROOT = BASE_DIR / 'staticfiles'Then collect all static files:
python manage.py collectstaticSecure Your Application with SSL
For any production Django application, HTTPS is non-negotiable. An SSL Certificate encrypts data in transit between your server and your users, protects sensitive information, and is required for modern browser trust indicators. AlexHost offers SSL certificates that integrate seamlessly with your hosting environment.
Additional Production Considerations
Environment Variables for Sensitive Settings
Never hardcode sensitive values like SECRET_KEY, database passwords, or API keys in settings.py. Use environment variables instead:
pip install python-decoupleIn settings.py:
from decouple import config
SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)Set DEBUG to False in Production
DEBUG = FalseRunning with DEBUG = True in production exposes detailed error pages and sensitive configuration information to potential attackers.
Configure a Domain Name
If you haven't already registered a domain for your Django project, Domain Registration through AlexHost makes it easy to get your domain pointed to your server quickly, with full DNS management included.
Choosing the Right Hosting for Your Django Application
The hosting environment you choose has a significant impact on your Django application's performance, reliability, and scalability. Here's a quick guide:
| Use Case | Recommended Hosting |
|---|---|
| Development & testing | Shared Web Hosting |
| Small to medium production apps | VPS Hosting |
| High-traffic or resource-intensive apps | Dedicated Servers |
| Machine learning / AI-integrated Django apps | GPU Hosting |
For most Django projects moving into production, a VPS Hosting plan offers the ideal balance of performance, control, and cost-effectiveness. You get root access, the ability to install any software stack, and dedicated resources that shared hosting cannot provide.
Troubleshooting Common Django Installation Issues
pip: command not found
Install pip manually: sudo apt install python3-pip -y
django-admin: command not found
Your virtual environment may not be activated. Run source venv/bin/activate and try again.
Port 8000 Not Accessible
Check your server's firewall rules. On Ubuntu with UFW:
sudo ufw allow 8000
sudo ufw reloadDatabase Connection Refused
Verify that your database service is running:
sudo systemctl status postgresql
# or
sudo systemctl status mysqlALLOWED_HOSTS Error
Ensure your server's IP address or domain name is listed in the ALLOWED_HOSTS setting in settings.py.
Conclusion
You have now successfully installed Django on your hosting server, configured a virtual environment, set up your database, and learned how to prepare your application for production. Django's rich feature set, strong security defaults, and massive ecosystem make it an excellent choice for web development projects of any scale.
For production deployments, always use a proper web server stack (Nginx + Gunicorn or Apache + uWSGI), set DEBUG = False, secure your application with an SSL Certificate, and choose a hosting environment that matches your application's resource requirements. Whether you're starting a new project or scaling an existing one, AlexHost's VPS Hosting and Dedicated Server plans provide the performance, reliability, and flexibility your Django application deserves.
on All Hosting Services
