Django is a python framework that was designed to support rapid web development. It is designed to be responsible for most of the web design work, such as sitemaps, content administration, authentication and more.
Since django is a python web framework, it requires python for it to be installed. You will need to first install python if you do not yet have it. Let us now start by installing django.
The first step is to install pip, which is a management system used to manages all packages and installs those that have been developed in python. Download the 'get-pip.py' file here or copy the file if it opens in a browser. After doing this, then run the
get-pip.py file with the command :
Set up a virtual environment. Python environments that are isolated are obtained from the virtual environment. This is a more practical way to use, compared to the other option where one could just install the package system for python globally. Another important advantage of using this method is that one can install any of the packages without having any administrative privileges. To install the virtual environment, run the following command:
pip install virtualenv
After installing the virtual environment, you will then need to set it up, using the following command:
Now that we have set it up, the next step is to activate it so that we can be able to use it. Use the following command to activate it:
Finally, we now need to install django. This can only happen after a successful creation and activation of the virtual environment. To do this, please use the following command:
pip install Django
We need to be sure that we have successfully installed django. To do that, type this command and see what the result it.
python -m django --version
What is your result? If you have done everything correctly above, then your result should show you the version of python that you have installed. My result shows 1.9.7.
An overview of Django
A web application developed in Django groups its code into different files, these files include 'views.py', 'templates', 'models.py' and 'urls.py'.
View: This is a function that acts as a request handler. It receives and returns HTTP requests and responses respectively. Views use models to get access to the data that is needed for the satisfaction of requests.
Template: These are mostly html files that are used to define or show how a file’s layout should look like by outlining its structure.
Models: These are objects in python, and are used to show how the data of an application is laid out. It also provides the ability to be able to add, delete, modify and query the database.
URLs: This is used by django to direct all the HTTP requests to the correct view, depending on the URL requested.
Developing a Django Application
We will go through a sample online shop that we will develop. We will handle the most important parts in this example, and by the end of it, you will be able to develop your own app using django.
So let's get started by creating the project in django
Creating the django e-commerce project
Follow the steps below to set up the django e-commerce project and application:
Create an empty directory for the django project. These directory will store all files related to your django project.
Navigate to the online_shop directory you have created above, then create a virtual environment and activate the virtual environment as shown below:
virtualenv venv``source venv/bin/activate
Install django in the virtual environment:
pip install django
Create a django project. The term project describes a Django web application. This involve specifying django-specific settings and application-specific settings for the django project. This process is usually automated by django. Type this command:
django-admin startproject my_online_shop
Navigate to my_online_shop directory and create a django application. A Django project usually contains several django applications. Create 'products' application by typing this command
python manage.py startapp products
Open the the external directory for the project - online_shop. Inside you will notice that django has created several folders for you. This is your application's root folder.
Now, we can verify if the django e-commerce project we have just created works well. Run the django development server by typing this command:
python manage.py runserver
Open your favorite browser, and paste this url http://127.0.0.1:8000/. You should see a page that says that 'It worked!'
The Django development server is running and that is why you are able to view the page in the browser. The inclusion of the development server together with django enables the developer to have a rapid development, having the production server already configured for them.
Setting up the database for the project
Download postgres and install on your platform by following this link. Then install the psycopg2 using the command below:
pip install psycopg2
Now that you have installed the postgres database and its bindings, we will create a database in postgres named 'online-shop'.
Am using postgres in a linux environment, and I will need to log into postgres account in order to create the database like this:
sudo -i -u postgres
After logging into postgres, I will use the PostgreSQL interactive terminal (psql) to create database using this SQL statement below.
CREATE DATABASE online_shop OWNER postgres;`
After creating the database, you will need to set the database configuration specifying the the database engine, name, user, password, host, and port in the my_online_shop/settings.py like this:
Lets create a model for our application 'products' we created earlier. In the products folder of our project, locate a 'models.py' file 'my_online_shop/products/models.py' and create a product model as shown in the code below.
from django.db import models from django.contrib.postgres.fields import JSONFieldclass Product(models.Model): class Meta: verbose_name = 'Product' verbose_name_plural = 'ProductS'name = models.CharField(null=False, blank= False, max_length=200) price = models.DecimalField(decimal_places=2, max_digits=1000, default=0) description = models.TextField(null=False, blank=False) image = models.CharField(null=True, blank=True, max_length=200)
In order to use the model above, you will need to do two things:
- First, include the products application in the INSTALLED_APPS settings in the my_online_shop/settings.py file.
Secondly, you will need to run migration. Migrations are Django’s way of propagating changes you make to your models To run migration, use the code below:
Python manage.py migrate
Adding products to the database table
After Django has created a table based on the model above, it will provide a database-abstraction API which you can use to create, retrieve and update records from the table. Now, let’s go into the interactive Python shell and use Django database API to add some products into our table. To invoke the Python shell, use this command:
python manage.py shell
Then use the code below to add products to the table.
from products.models import Product a = Product(name='iPhone 7', price='78999', description='A10 fusion\ chip, 12MP Camera, Retina HD Display, Immersive stereo speakers') a.save() b = Product(name='Samsung Galaxy S8 Rumors', price='75966', description='Snapdragon Qualcomm octa-core 3.2 GHz processor, 6GB RAM, 30MP Camera, retina eye scanner, wireless charging, rapid charging, mini projector') b.save()
This tutorial has enabled us to create a django application and connect it to a postgres database. This is a simple application, that introduces you to Django, and creates a simple application for you. Following this tutorial, you can easily create more applications in Django.