Write Review

By now you understand what Django is for. If you have used the framework extensively, you may have noticed that the biggest problem is that a new project created in one Django version may not be compatible with a different one. For instance, if the project was created with Django 1.5x and you happen to upgrade to Django 1.6x, your project may refuse to run.

A simple solution to this issue is to stick with one version of Django for all your projects. Then you can use virtualenv to create a virtual environment with its own installation directories. Virtualenv allows for installation of a custom Python version with its packages.

In this tutorial, we will look at how to install Django by creating a virtual environment (also known as virtualenv) and how to set up a new project.

Virtualenv:

Before installing Django, it’s recommended to install Virtualenv that creates new isolated environments to isolates your Python files on a per-project basis. This will ensure that any changes made to your website won’t affect other websites you’re developing. The interesting part is that you can create virtual environments with different python versions, with each environment having its own set of packages.

In this article, we are going to use Python version 3 to install Virtualenv.

Step 1: Creating a new virtual environment

Depending on the Python version you intend to use, start by creating a virtual environment. In this case, we will install virtualenv using Python 3.

Virtualenv is the most recommended way to configure a Python environment.

To run these commands, ensure you’re logged into your main server through SSH with your Shell user.

Use pip3 to install Virtualenv.

These instructions assume that you’ve a custom Python 3 version installed on your computer. Once it’s installed, run pip3 to start installing virtualenv as follows:

[server]$ pip3 install virtualenv
Collecting virtualenv
  Downloading virtualenv-15.1.0-py2.py3-none-any.whl (1.8MB)
  100% |████████████████████████████████| 1.8MB 367kB/s
Installing collected packages: virtualenv
Successfully installed virtualenv-15.1.0

You will need full access to virtualenv’s Python 3 version, so run the command below to view it:

[server]$ which virtualenv
/home/username/opt/python-3.6.2/bin/virtualenv

Create a new isolated environment with custom Python version

When working with Python’s virtual environment, it’s recommended to use the custom Python version rather than the server’s version. Follow the steps below to create a new virtual environment using Python’s custom installed version.

Make sure you have full file of the custom Python version installed. You should have something like this:

[server]$ which python3
/home/username/opt/python-3.6.2/bin/python

Head over to the site’s directory and create a virtual environment as shown below:

[server]$ cd ~/example.com

After creating your virtual environment, don’t forget to specify the Python version you want to use. In this case, the following command helps to create “my project” in the first path with the –p flag to identify the full path to the version of Python 3 installed:

[server]$ virtualenv ~/example.com/my_project -p /home/example_username/opt/python-3.6.2/bin/python3
 
Running virtualenv with interpreter /home/example_username/opt/python-3.6.2/bin/python3
Using base prefix '/home/example_username/opt/python-3.6.2'
New python executable in /home/example_username/example.com/env/bin/python3
Also creating executable in /home/example_username/example.com/env/bin/python
Installing setuptools, pip, wheel...done.

While working with this command, make sure the local environment is active to confirm you have the right versions of packages and tools.

Activate your virtual environment by typing:

[server]$ source my_project/bin/activate

The name of your virtual environment should appear at the beginning of the prompt as follows:

(my_project) [server]$

To confirm you have the right version of Python, run the command below:

[server]$ python -V
Python 3.6.2

By now, any packages installed using pip is in your virtual environment directory.

When you’re done working with your virtual environment, you go ahead and deactivated by typing:

[server]$ deactivate

This should set your Shell user to default settings.

To delete your virtual environment, run the command below:

[server]$ rm -rf /home/username/example.com/my_project

Step 2: Installing Django on Virtualenv

Pip tool makes it easy to run Django in Virtualenv. It’s a simple tool used to install your packages. In some systems, it is recommended to have installed python-dev to run virtualenv successfully. It’s also important to upgrade pip to the latest version before the installation of virtualenv.

In most systems, you can simply install the two by typing the following commands:

sudo apt-get install python-pip python-dev
sudo pip install -upgrade pip

If you’re using Python 3 version to install Django, use the command below:

(my_project) [server]$ pip3 install Django
(my_project) [server]$ pip3 install mysqlclient

In other systems, follow the official instructions of pip to begin your installation process. This post assumes that your virtual project has a requirements.txt file. This file is found in the python repository and contains all packages with their corresponding versions needed to run and install the project successfully.

PIL
python-dateutil==1.5
django-guardian==1.1.0.beta
south
djangorestframework
markdown
django-filter
pyyaml
defusedxml
django-oauth-plus
django-oauth2-provider

Generate the requirements of your projects by running the command “pip freeze” to list all the installed packages in your computer with all the available versions.

pip freeze > requirements.txt

At times, this process can generate unwanted packages in the requirements file installed in your computer, so ensure you edit this file manually.

Create your virtual environment by typing this command:

virtualenv <environment_name>

Note that this command may create two different directories as follows:

<environment_name>/lib/pythonX.X/site-packages

(Installed python files will go here)

<environment_name>/bin/python/

(Python interpreter libraries for your virtual environment will be found here)

You can choose to either add the option –no-site-packages or –system-site-packages with the above command to specify whether you want to receive all these installed packages or not.

To activate the virtual environment, type:

source ./<environment_name>/bin/activate

At your command prompt, you should see something like this:

(<environment_name>) $

This shows that you’re running the correct virtualenv install.

Move your project details to the virtualenv directory by running the following command:

pip install requirements.txt

By now you should have a fully installed Django on Virtualenv.

Step 3: Creating a new Django Project on Virtualenv

Now that you have created a virtual environment, you can move on to create a Django project.

To start, run the command below to create your project on Django:

[server]$ cd $HOME/example.com
[server]$ source $HOME/example.com/my_project/bin/activate
(my_project) [server]$ python my_project/bin/django-admin.py startproject <projectname>
  • Replace the name with a description of your choice.

To make it easier for a Passenger to identify your project, create a _wsgi. py file within your website’s directory. You should have something like this:

import sys, os
INTERP = "/home/<username>/local/bin/python"
#INTERP is present twice so that the new python interpreter
#knows the actual executable path
if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv)
 
cwd = os.getcwd()
sys.path.append(cwd)
sys.path.append(cwd + '/djangoprojectname')  #You must add your project here
 
sys.path.insert(0,cwd+'/my_project/bin')
sys.path.insert(0,cwd+'/my_project/lib/python2.7/site-packages')
 
os.environ['DJANGO_SETTINGS_MODULE'] = "djangoprojectname.settings"
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

Start setting up static files on Django to correctly serve CSS, images, and Javascript as you will need them for the admin interface to work.

  • Go to projects .py file located in the following spot:
example.com/projectname/settings.py

Then scroll down to the bottom where you will find the Static_URL, it should be configured to /static/.

Include another line to set the location of the static directory as follows:

STATIC_ROOT = os.path.dirname(BASE_DIR) + '/static/'

In your public directory, ensure you create following /static directory where the Django will store all your static files:

(my_project) [server]$ cd $HOME/example.com/public
(my_project) [server]$ mkdir static

Proceed to run the collectstatic command to prepare the static files for the admin interface.

(my_project) [server]$ cd $HOME/example.com/projectname/
(my_project) [server]$ python manage.py collectstatic

Within the setting.py file, set your database as follows:

DATABASES = {
  'default': {
    	'ENGINE': 'django.db.backends.sqlite3',
    	'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
  }
}

Edit the information to fit your actual credentials.

DATABASES = {
  'default': {
    	'ENGINE': 'django.db.backends.mysql',
    	'NAME': 'mydatabase',
    	'USER': 'mydatabaseuser',
    	'PASSWORD': 'mypassword',
    	'HOST': 'mysql.example.com',
    	'PORT': '3306',
  }
}

In the settings.py file, update the field labelled ALLOWED-HOSTS with your name to have something like this:

ALLOWED_HOSTS = ['example.com' , 'www.example.com']

Ensure the information is in your Django project directory:

(my_project) [server]$ cd ~/example.com/<projectname>

Once the configuration is done, run migrate on your directory:

(my_project) [server]$ python manage.py migrate
Operations to perform:
 Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
 Applying contenttypes.0001_initial... OK
 Applying auth.0001_initial... OK
 Applying admin.0001_initial... OK
 Applying admin.0002_logentry_remove_auto_add... OK
 Applying contenttypes.0002_remove_content_type_name... OK

Then create your superuser:

(my_project) [server]$ python manage.py createsuperuser
Username (leave blank to use 'username'): my_django_user
Email address: email@example.com
Password:
Password (again):
Superuser created successfully.

Go to directory and add the following text; /tmp/restart.txt file:

(my_project) [server]$ cd /home/username/example.com
(my_project) [server]$ mkdir tmp
(my_project) [server]$ cd tmp
(my_project) [server]$ touch restart.txt

Once you make these changes, ensure you run this command in your project directory:

(my_project) [server]$ touch tmp/restart.txt

Confirm the Django project is successfully installed on your site:

Now you should be able to access the admin page on Django.

Conclusion

If you follow these steps correctly, install the right versions of Pythons, and everything else, then you should have a successfully installed Django. We hope this guide will be helpful.

Check out these top 3 Django hosting services:

Was this article helpful?