Django tutorial

What is a Web Framework?

A web framework is a code library which helps you to build a flexible, scalable, and maintainable, dynamic website, web app, and web services. Different web frameworks are Zend for PHP, Ruby on Rails for Ruby, etc.

What is Django?

Django is a web development framework for Python which offers a standard method for fast and effective website development. It helps you to assists in building and maintaining quality web applications. It enables you to make the development process smooth and time-saving.

It is a high-level web framework which allows performing rapid development. The primary goal of this web framework is to create complex database-driven websites.

Install Django 2 in Mac with Pip and Virtual Env

brew install python
pip3
python3
python3 -m venv env2
cd env2
cd ..
source env2/bin/activate
which python 
pip3 install django 
pip install --upgrade pip
django-admin startproject tasks
cd tasks
ls
python manage.py runserver

For Mac OSX: There is a way to install Visual Studio Code through Brew-Cask.

First, install ‘Homebrew’ from here.
Now run following command and it will install the latest Visual Studio Code on your Mac.

$> brew cask install visual-studio-code

bove command should install Visual Studio Code and also set up the command-line calling of Visual Studio Code.

Hello world Django 2.2

python manage.py startapp pages

Inside the directory

college/settings.py

INSTALLED_APPS = [
     'django.contrib.admin',
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'pages.apps.PagesConfig', # new
 ]

pages/views.py

# pages/views.py
from django.http import HttpResponse

def homePageView(request):
    return HttpResponse('Hello, World!')

Create inside of pages URL

touch pages/urls.py

Then update it with the following code:

pages/urls.py

# pages/urls.py
from django.urls import path

from .views import homePageView

urlpatterns = [
    path('', homePageView, name='home')
]

college/urls.py

# college/urls.py
from django.contrib import admin
from django.urls import path, include  # new

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('pages.urls')),  # new
]

Run server

python manage.py runserver

How to use HTML file in Django

First, we need to add templates folder or whatever folder you want to create you can within route directory

Now inside of settings.py file, we need to set ‘DIRS’ path within templates

'DIRS': [os.path.join(BASE_DIR, 'templates')],

Now to need to go inside of views.py

import render like below code

from django.shortcuts import render

Load view inside the function

def homePageView(request):
        return render(request,'home.html')

Django Template Language

How to use Django Template Language

We need to import render package

than define within views

def aboutPageView(request):
        return render(request, "about.html", {'name': 'Real Programmer'})

Now print name within about.html

{{ name }}

Here, I created a file with the name of base.html. inside of base.html, I’m going to put some code like within body tag

<body style="background: red;">
    {% block content %}
        
    {% endblock  %}
</body>

Now, Just open file about.html

{% extends 'base.html' %}

{% block content %}
<h1>{{ name }}</h1>
{% endblock %}

GET VS POST Example

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<div class="container">
    <form action="contact_submit" method="GET">
        <div class="form-group">
            <label >Name</label>
            <input type="text" class="form-control" placeholder="Enter Name" name="name">
        </div>
        <div class="form-group">
            <label>Email</label>
            <input type="text" class="form-control" placeholder="Enter Email" name="email">
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>
</div>

Load page view within urls.py and then print data which is coming from the get method

from .views import contactPageView, contact_submitPageView
path('contact', contactPageView, name='contact'),
path('contact_submit', contact_submitPageView, name='contact_submit'),

Now, urls.py function create

def contact_submitPageView(request):
         name = request.GET['name']
         email = request.GET['email']
         result = name + email
         return render(request, "contact.html", {'result': result})

Now, print result witin contact.html

<h1>{{ result }}: About Page</h1>

POST Method

 <form action="contact_submit" method="POST">
        {% csrf_token %}
        <input type="text" name="name">
        <input type="text" name="email">
        <input type="submit">
  </form>

Now, add code within urls.py

from .views import contact_submitPageView

path('contact_submit', contact_submitPageView, name='contact_submit'),

Now, add code within views

def contact_submitPageView(request):
         name = request.POST['name']
         email = request.POST['email']
         result = name + email
         return render(request, "contact.html", {'result': result})

Now, print result witin contact.html

<h1>{{ result }}: About Page</h1>

How to load a static file in Django 2.2

Open setting.py file and put code like

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

STATIC_ROOT = os.path.join(BASE_DIR, 'assets')

Then, run the command

python manage.py collectstatic

Open, HTML file and put code like

{% load static %}

Inside of HTML link, we need to put code like

Example:

Images: {% static '/imgs/bird.jpg' %}
Css:    {% static '/css/bird.cs' %}
JS:    {% static '/js/bird.js' %}

Passing Dynamic Data in Html

Add code to model

# Create your models here.
class Blog():
    id: int
    name: int
    img: str
    desc: str
    price: int

Add a package to views(views.py)

from .models import Blog

def homePageView(request):
        dest = Blog()
        dest.name = "sid"

        dest2 = Blog()
        dest2.name = "sid"

        dests = [dest, dest2]
        return render(request, "home.html", {'dests': dests})

Print data to HTML page

{% for dests in dests %}
        <h1>{{ dests.name }}</h1>
 {% endfor %}
Leave a Comment