How to Install, Setup and Create a App in Django step by step
What is Django?
Django is a free and open-source web framework of Python that follows the model–template–views architectural pattern. It is maintained by the Django Software Foundation. Django makes it easier to build better Web apps more quickly and with less code. It is among the most famous web frameworks and one of the most used frameworks as well. It is used by Instagram, YouTube, Google and even NASA for their websites.
In this post, We’ll learn how one can start working with Django project quickly Step by step and Some basics Django Framework.
Advantages of Django:
- Simplicity: Django is written in Python. The Python language is simple to learn.
- Pluggable: Django is pluggable by nature and can be extended with plugins.
- Rich set of Libraries: Django comes with its own set of libraries for solving common tasks. A software library includes prewritten code, classes, procedures, scripts, configuration data, and more. This reduces time to market.
- ORM: ORM stands for Object-Relational Mapping (ORM) is a programming technique for converting data between relational databases and object oriented programming languages.
- Community: Django has very active community and they are actively working on making the framework more beginner-friendly and stabilizing the framework while adding new features.
- Built-in admin: Django offers build in admin console to manage your data with basic CRUD operations.
Lets now create a Simple Django App following the below steps:
You Should install Python on Your machine. Youcan check if python is installed or not using below command. If not installed, Please install it.
thedevopsguy@WS-7608:~$ python3 --version
Python 3.8.5
We need pip to be installed on your machine as a Prerequisite.pip is one of the most famous and widely used package management system to install and manage software packages written in Python. pip stands for preferred installer program. Please use below command to install pip.
thedevopsguy@WS-7608:~$ sudo apt install python3-pip
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
binutils binutils-common binutils-x86-64-linux-gnu build-essential cpp cpp-9 dpkg-dev fakeroot g++ g++-9 gcc gcc-9 gcc-9-base libalgorithm-diff-perl
libalgorithm-diff-xs-perl libalgorithm-merge-perl libasan5 libatomic1 libbinutils libc-dev-bin libc6-dev libcc1-0 libcrypt-dev libctf-nobfd0 libctf0 libdpkg-perl
libexpat1-dev libfakeroot libfile-fcntllock-perl libgcc-9-dev libgomp1 libisl22 libitm1 liblsan0 libmpc3 libpython3-dev libpython3.8 libpython3.8-dev
libpython3.8-minimal libpython3.8-stdlib libquadmath0 libstdc++-9-dev libtsan0 libubsan1 linux-libc-dev make manpages-dev python-pip-whl python3-dev python3-wheel
python3.8 python3.8-dev python3.8-minimal zlib1g-dev
You can check if pip installed or not and the installed version using below command.
thedevopsguy@WS-7608:~$ pip --version
pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.8)
In order to work with python, it is always suggested to setup virtual environment.
A virtual environment helps to keep dependencies required by different projects and This is one of the most important tools that most of the Python developers use. Consider a scenario where you are working on two web based python projects on the same machine and one of them uses a Django 1.10 and the other uses Django 1.13 and so on. In such situations virtual environment can be really useful to maintain dependencies of both the projects.
thedevopsguy@WS-7608:~$ python3 -m venv my-project-env
thedevopsguy@WS-7608:~$ ll
total 0
drwxr-xr-x 1 thedevopsguy thedevopsguy 4096 May 26 10:47 git
drwxr-xr-x 1 thedevopsguy thedevopsguy 4096 May 26 11:05 raw
drwxr-xr-x 1 thedevopsguy thedevopsguy 4096 May 29 17:12 my-project-env
Now virtual environment is setup on your machine but inorder to use we need to activate it first.
thedevopsguy@WS-7608:~$ source my-project-env/bin/activate
(my-project-env) thedevopsguy@WS-7608:~$
Now we can check if django is installed or not using below command.
(my-project-env) thedevopsguy@WS-7608:~$ django-admin --versionCommand 'django-admin' not found, but can be installed with:
If not installed Please use below command to install django.
(my-project-env) thedevopsguy@WS-7608:~$ pip install django
Collecting django
Downloading Django-3.2.3-py3-none-any.whl (7.9 MB)
|████████████████████████████████| 7.9 MB 3.2 MB/s
Collecting asgiref<4,>=3.3.2
Use below command to create a first Project in Django.
(my-project-env) thedevopsguy@WS-7608:~$ django-admin startproject demoproject
It will create a below directory Structure for you. Out of which settings.py is your main configuration file. It holds all the configuration values that your web app needs to work like database settings, logging configuration, where to find static files and a bunch of other stuff. urls.py is where you define the mapping between URLs and views. manage.py is a A command-line utility that lets you interact with this Django project in various ways.it will help you to host your Application, help with Performing various database activities etc. This are the three basic files you should know inorder to work with Simple Django App.
(my-project-env) thedevopsguy@WS-7608:~/demoproject$ tree
.
├── demoproject
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
Now Django is installed and setup. You can run below command to host the application on your local machine.It will start Start a Server in the backend and if you hit the http://127.0.0.1:8000/ url in browser you can see default first page.Django default use 8000 port.
(my-project-env) thedevopsguy@WS-7608:~$ cd demoproject/
(my-project-env) thedevopsguy@WS-7608:~/demoproject$ python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...System check identified no issues (0 silenced).You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
June 04, 2021 - 08:02:50
Django version 3.2.3, using settings 'demoproject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Lets create a simple Hello World Application now using the below steps. if you hit http://127.0.0.1:8000/helloworld/ url then it should open hello world Application.
In Django it is always a best practice to create a different Apps under a project to segregate the Big Project into small Functionality wise modules. For example if you have a large project with functionality like login part,admin utility,customer interaction etc. it is always recommended to create app for each of the functionality under Project.
Now we will create a helloworld app under demoproject. Please follow below command to create app.
(my-project-env) thedevopsguy@WS-7608:~/demoproject$ python manage.py startapp helloworld
(my-project-env) thedevopsguy@WS-7608:~/demoproject$ ll
total 4
drwxr-xr-x 1 thedevopsguy thedevopsguy 4096 Jun 4 13:53 ./
drwxr-xr-x 1 thedevopsguy thedevopsguy 4096 Jun 4 12:40 ../
-rw-r--r-- 1 thedevopsguy thedevopsguy 0 May 31 15:17 db.sqlite3
drwxr-xr-x 1 thedevopsguy thedevopsguy 4096 May 31 15:32 demoproject/
drwxr-xr-x 1 thedevopsguy thedevopsguy 4096 Jun 4 13:53 helloworld/
-rwxr-xr-x 1 thedevopsguy thedevopsguy 667 May 31 15:14 manage.py*
Lets follow the below steps carefully.
Step 1: navigate to helloworld app and create urls.py under it and paste the below content. This urls.py us App level urls.py and django does not create is automatically. We has to create this file.
(my-project-env) thedevopsguy@WS-7608:~/demoproject$ cd helloworld/
(my-project-env) thedevopsguy@WS-7608:~/demoproject/helloworld$ cat urls.py
from django.urls import path
from . import viewsurlpatterns = [
path('',views.helloworld,name='helloworld')
]
Step 2 : inside views.py from the helloworld App, Please add the below content.
(my-project-env) thedevopsguy@WS-7608:~/demoproject/helloworld$ cat views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.def helloworld(request):
return render(request,’helloworld.html’)
Step 3 : Inside Project level urls.py file Please Add below highlighted content.
from django.contrib import admin
from django.urls import path,includeurlpatterns = [
path('admin/', admin.site.urls),
path('helloworld/',include('helloworld.urls')),
]
Step 4: Create a template directory at the root of the Project and create helloworld.html file inside it.
(my-project-env) thedevopsguy@WS-7608:~/demoproject$ cd templates/
(my-project-env) thedevopsguy@WS-7608:~/demoproject/templates$ ll
total 0
drwxr-xr-x 1 thedevopsguy thedevopsguy 4096 Jun 4 16:11 ./
drwxr-xr-x 1 thedevopsguy thedevopsguy 4096 Jun 4 16:22 ../
-rw-r--r-- 1 thedevopsguy thedevopsguy 73 Jun 4 16:11 helloworld.html
(my-project-env) thedevopsguy@WS-7608:~/demoproject/templates$ cat helloworld.html
<!DOCTYPE html>
<html>
<body><h1>Hello World</h1></body>
</html>
Step 5 : go to Project level settings.py file and specify the html template directory as highlighted below.
TEMPLATES = [
{
‘BACKEND’: ‘django.template.backends.django.DjangoTemplates’,
‘DIRS’: [os.path.join(BASE_DIR,’templates’)],
‘APP_DIRS’: True,
‘OPTIONS’: {
‘context_processors’: [
‘django.template.context_processors.debug’,
‘django.template.context_processors.request’,
‘django.contrib.auth.context_processors.auth’,
‘django.contrib.messages.context_processors.messages’,
],
},
},
]
Your Application is ready now. Please hit http://127.0.0.1:8000/helloworld/ url in the browser to access the Application.
How Flow works?
When any user hit any url (i.e. in our case /helloworld) Django will first check Project level urls.py and if its match with given url then it will forward request to App level urls.py. if not found then it will throw 404 error.App urls.py will forward request to views.py where we have define the actual buissness login. Views.py then forward request to the defined html Page and then our request is rendered on browser.