The virtual environment is used by Django to execute an application. It is recommended to create and execute a Django application in a separate environment. Python itself provides “virtualenv” tool to create an isolated Python environment. We can use this tool to create a virtual environment for the Django application.
To set up a virtual environment, we will use the following steps.
1. Install Package
First of all, we have to install python3-venv package by using the following command.
$ apt-get install python3-venv
2. Create a Directory
$ mkdir djangoenv
After this, we will change the directory to the newly created directory by using the “cd djangoenv”.
3. Create Virtual Environment
$ python3 -m venv djangoenv
4. Activate Virtual Environment
After creating the virtual environment, we will activate it by using the following command.
$ source djangoenv/bin/activate
Now, the virtual environment has started and we can use it to create Django application.
To install Django, first, we have to visit the Django official site (https://www.djangoproject.com) and download Django by clicking on the download section.
Django requires pip to start the installation. Pip is a package management system that is used to install and manage the packages written in python. pip3 is used to manage packages for Python 3.4 and higher versions.
Before installing the Django, make sure that pip is installed in your local system.
Here, we are installing Django using pip3 and the installation command is given below.
$ pip3 install django==2.0.3
After installing the Django, we need to verify the installation.
Open the terminal and write python3 and then press enter. It will display the python shell where we can verify the Django installation.
Write “print(Django.get_version())” and the Django version will be displayed on the terminal. Now, Django is installed successfully and we can build Django web applications.
To run the web application Django uses its built-in development server. To start this server, we use the “python manage.py runserver” command.
This command starts the server which runs on port 8000 and can be accessed at the browser by entering localhost:8000.
But if we want to run our application by using the apache server then we need to configure the apache2.conf file located at /etc/apache directory. We have to add the following code in this file.
WSGIScriptAlias / /var/www/html/django7/django7/wsgi.py WSGIPythonPath /var/www/html/django7/
<Directory /var/www/html/django7> <Files wsgi.py> Require all granted </Files> </Directory>
After adding these lines, we have to restart the apache server by using the “service apache2 restart” command and then type localhost to the browser's address bar. Now, the project will run on the apache server rather than a built-in server.