# Django Tutorial for Beginners
###### tags: `Django` `Beginners` `Telusko`
{%youtube OTmQOjsl0eg %}
- [Github for Code](https://github.com/navinreddy20/django-telusko-codes)
- [Travello Template](https://www.dropbox.com/sh/gf8x8xjwidq20cz/AABPlOsXmijnz0-yjxYj9ebsa?dl=0)
> 1. What is Django? – 00:05
> 2. Django Setup – 05:05
> 3. First App in Django (Part-1) – 16:03
> 4. First App in Django (Part-2) – 24:21
> 5. Django Template Language (DTL) (Part-1) – 31:57
> 6. Django Template Language (DTL) (Part-2) – 40:31
> 7. Addition of two Numbers in Django – 44:15
> 8. GET vs POST HTTP Methods – 52:24
> 9. Model View Template (MVT) – 58:19
> 10. Static Files 1 – 01:04:02
> 11. Static Files 2 – 01:11:14
> 12. Passing Dynamic Data in HTML (Part-1) – 01:21:05
> 13. Passing Dynamic Data in HTML (Part-2) – 01:31:46
> 14. If Statement in Django – 01:41:30
> 15. Object Relational Mapper (ORM) – 01:46:52
> 16. Postgres and PgAdmin Setup – 01:51:20
> 17. Models & Migrations – 01:56:15
> 18. Re-Migration – 02:08:14
> 19. Admin Panel – 02:10:58
> 20. Add & Fetch Data from Database – 02:16:59
> 21. User Registration in Django (Part-1) – 02:25:55
> 22. User Registration in Django (Part-2) – 02:39:25
> 23. Passing Message in Django – 02:49:27
> 24. User Login – 02:56:00
> 25. User Logout – 03:03:59
> Happy Learning.:smile:
---
## :gear: Installing Python & Django
The Python Package Repository (PyPi), using the pip tool, is the best way to get the latest stable version of Django.
:
### Step 1: Installing Python 3
In order to use Django you will have to install Python on your operating system. If you're using Python 3 then you will also need the [Python Package Index](https://pypi.org/) tool — pip3 — which is used to manage (install, update, and remove) Python packages/libraries used by Django and your other Python apps.
This section briefly explains how you can check what versions of Python are present, and install new versions as needed, for Ubuntu and Windows.
#### ==**Ubuntu**==
Ubuntu Linux 20.04 LTS includes Python 3.8.5 by default. You can confirm this by running the following command in the bash terminal:
```shell=1
python3 -V
Python 3.8.5
```
However, the Python Package Index tool *(pip3)* you'll need to install packages for Python 3 (including Django) is **not** available by default. You can install pip3 in the bash terminal using:
```shell=1
sudo apt install python3-pip
```
#### ==**Windows**==
Windows doesn't include Python by default, but you can easily install it
1. Download the required installer:
i. Go to [python.org](https://www.python.org/downloads/)
ii. Select the **Download Python 3.8.6** button (the exact version number may differ).
2. Install Python by double-clicking on the downloaded file and following the installation prompts
3. Be sure to check the box labeled "Add Python to PATH"
You can then verify that Python 3 was installed by entering the following text into the command prompt:
```cmd=1
py -3 -V
Python 3.8.6
```
The Windows installer incorporates pip3 (the Python package manager) by default. You can list installed packages as shown:
```cmd=1
pip3 list
```
### Step 2: Installing the virtual environment software
:::info
:thinking_face: **Why a virtual environment?** ➜ [Check this post](https://medium.com/incwell-bootcamp/virtual-environment-in-python-54db665b9939)
:::
#### :computer: Ubuntu virtual environment setup
1. To install virtualenvwrapper (which includes virtualenv) follow the instructions below.The official installation guide can be found [here](https://virtualenvwrapper.readthedocs.io/en/latest/install.html). Install the tool using pip3:
```shell=1
sudo pip3 install virtualenvwrapper
```
2. Then add the following lines to the end of your **shell startup file** (this is a hidden file name **.bashrc** in your home directory). These set the location where the virtual environments should live, the location of your development project directories, and the location of the script installed with this package:
```bash=1
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
export VIRTUALENVWRAPPER_VIRTUALENV_ARGS=' -p /usr/bin/python3 '
export PROJECT_HOME=$HOME/Devel
source /usr/local/bin/virtualenvwrapper.sh
```
:::info
:memo: **Note:** The ```VIRTUALENVWRAPPER_PYTHON``` and ```VIRTUALENVWRAPPER_VIRTUALENV_ARGS``` variables point to the normal installation location for Python3, and ```source /usr/local/bin/virtualenvwrapper.sh``` points to the normal location of the virtualenvwrapper.sh script. If the *virtualenv* doesn't work when you test it, one thing to check is that Python and the script are in the expected location (and then change the startup file appropriately).
You can find the correct locations for your system using the commands ```which virtualenvwrapper.sh``` and ```which python3```.
:::
Then reload the startup file by running the following command in the terminal:
```shell=1
source ~/.bashrc
```
#### :desktop_computer: Windows virtual environment setup
Installing [virtualenvwrapper-win](https://pypi.python.org/pypi/virtualenvwrapper-win) is even simpler than setting up virtualenvwrapper because you don't need to configure where the tool stores virtual environment information (there is a default value). All you need to do is run the following command in the command prompt:
```cmd=1
pip3 install virtualenvwrapper-win
```
### Step 3: Creating a virtual environment
Once you've installed virtualenvwrapper or virtualenvwrapper-win then working with virtual environments is very similar on all platforms.
Now you can create a new virtual environment with the ```mkvirtualenv``` command.
When the command completes the new virtual environment will be active — you can see this because the start of the prompt will be the name of the environment in brackets, as below.

Now you're inside the virtual environment and can install Django to start developing.
:::info
:memo: **Note: Using a virtual environment**
:::info
There are just a few other useful commands that you should know (there are more in the tool documentation, but these are the ones you'll use regularly):
- ```deactivate``` — Exit out of the current Python virtual environment
- ```workon``` — List available virtual environments
- ```workon name_of_environment``` — Activate the specified Python virtual environment
- ```rmvirtualenv name_of_environment``` — Remove the specified environment.
:::
### Step 4: Installing Django
Once you've created a virtual environment, and called ```workon``` to enter it.
```shell=1
workon name_of_environment
```
And then use pip3 to install Django.
```shell=1
pip3 install django
```
You can test that Django is installed by running the following command (this just tests that Python can find the Django module):
```shell=1
# Linux/macOS
python3 -m django --version
3.1.2
# Windows
py -3 -m django --version
3.1.2
```
### Step 5: Testing your installation
Now let's create a skeleton project and see it working. To do this, first navigate in your command prompt/terminal to where you want to store your Django apps. Create a folder for your test site and navigate into it.
```bash=
mkdir django-projects
cd django-projects
```
You can then create a new skeleton site called "mytestsite" using the django-admin tool as shown. After creating the site you can navigate into the folder where you will find the main script for managing projects, called manage.py.
```bash=
django-admin startproject mytestsite
cd mytestsite
#Make sure you are in your virtual environment
```
We can run the development web server from within this folder using **manage.py** and the runserver command, as shown.
```bash=
python3 manage.py runserver
```

:::info
:memo: **Note:** The above command shows the Linux/macOS command. You can ignore the warnings about "18 unapplied migration(s)" at this point!
:::
Once the server is running you can view the site by navigating to the following URL on your local web browser: http://127.0.0.1:8000/. You should see a site that looks like this:

:::success
### **Congratulations!**
You now have a Django development environment up and running on your computer.
:::
---
## :gear: Installing a DBMS for Django
#### :computer: ==**Ubuntu environment**==
#### Installing PostgreSQL
Following installation steps from official site [postgresql.org](https://www.postgresql.org/download/linux/ubuntu/) or as below:
#### Step 1: Add To APT Repository and Install PostgreSQL
```
#Create the file repository configuration:
sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
#Import the repository signing key:
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
#Update the package lists and install latest version
sudo apt-get update
sudo apt-get -y install postgresql
```
#### Step 2: Create PostgreSQL Linux User Password:
```shell=1
sudo passwd postgres
```
You should be prompted to create a new Linux password for postgres user.

#### Step 3: Accessing PostgreSQL:
Now that PostgreSQL is installed, to access its interactive shell and manage databases, you need to log in as the postgres user. To do so run the commands below:
```shell=1
#Use any of the below commands
#Sys prompt to give 'current' user password
sudo su -l postgres
#Sys prompt to give 'postgres' user password
su postgres
```
:::info
:memo: Know more about **[sudo](https://phoenixnap.com/kb/linux-sudo-command)** & **[su](https://phoenixnap.com/kb/su-command-linux-examples)** commands.
:::
You should now be in the interactive shell. By default there is a *superuser role* **postgres**.
You may set a password for this role as below:

:::info
:memo: What to create a different role? Know more about **[PostgreSQL roles](https://docs.rackspace.com/support/how-to/postgresql-creating-and-dropping-roles/)**.
:::
#### Step 4: Install pgadmin4:
Follow installation steps from official site [pgadmin.org](https://www.pgadmin.org/download/pgadmin-4-apt/) or as below:
```shell=1
#
# Setup the repository
#
# Install the public key for the repository (if not done previously):
sudo curl https://www.pgadmin.org/static/packages_pgadmin_org.pub | sudo apt-key add
# Create the repository configuration file:
sudo sh -c 'echo "deb https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/$(lsb_release -cs) pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list && apt update'
#
# Install pgAdmin
#
# Install for both desktop and web modes:
sudo apt install pgadmin4
# Configure the webserver, if you installed pgadmin4-web:
sudo /usr/pgadmin4/bin/setup-web.sh
```
#### Step 5: Creating a sever using pgadmin4:
After opening pgadmin, we can create a new sever as below:

You may give any valid name for the server.

In the *Connection* tab the username is actually one of the PostgreSQL roles. We are using the default **postgre** superuser role.

Finally, we created our first server using pgadmin4.

:::info
:memo: Know more on usage of **[pgadmin4](https://linuxhint.com/pgadmin4_tutorial_beginners/)**.
:::
#### Additional Steps
After PostgreSQL is installed, you can confirm that the PostgreSQL service is active, running and is enabled under systemd using the following systemctl commands:
```shell=1
sudo systemctl is-active postgresql
sudo systemctl is-enabled postgresql
#Few other commands
sudo systemctl start postgresql
sudo systemctl stop postgresql
sudo systemctl enable postgresql
sudo systemctl status postgresql
sudo nano /etc/postgresql/<version_no>/main/pg_hba.conf
```

Also, confirm that the Postgresql server is ready to accept connections from clients as follows:
```shell=1
sudo pg_isready
```

---
## :gear: Architecture of Django Framework
Django uses MVT (Model-View-Template).
In MVT architecture, **Model** is similar to the model component of MVC wherein it is used to manage data. However, the business logic is managed by the **View** instead of the Model. **Template** is a HTML document that uses the Django Template Language (DTL).
Here's what happens once Django accepts the client request :-
1. Based on the requested URI (Uniform Resource Identifier), it selects the View.
2. The View interacts with the corresponding Model for the required data.
3. The Model returns the database objects requested by the View.
4. The View then processes the data and renders the required template along with Model data as a response back to the client.
The same is illustrated as given below.

:::info
:pushpin: Want to learn more? Here are few places to check..
* [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django)
* [Learn Django By Example](https://docs.djangoproject.com/en/3.2/intro/tutorial01/)
:::
> [name=Abhishek Dev]