DJango

1. Configuration of Django
2. Project Structure
3. Creating a new project
4. Running Django application
5. Login to a new project using notepad++
6. Templates
7. Template Variables
8. Run existing project
9. Output in table format
10. Types of tags used in Django
11. if tag and if else tag
12. for tag
13. Internal Hyperlinks
14. External Hyperlinks
15. Dynamic Loading of Web Pages
16. Images/ Audio files in web page
17. Comment tag
18. Django Forms
19. Form Field Elements
20. Feedback Form
21. Redirection of feedback form to new form
22. Employee Form
23. Employee Form with Choice Field and redirection to new form
24. Multiple Choice Fields
25. SQLite Installation
26. Model Field Elements
27. Department Model Form
28. Employee Model Form
29. CSS/ Bootstrap
30. CSS for table format output
31. Primary and Foreign Key concepts in DJango
32. DJango Project 01
33. DJango Project 02 – Password Generator


1. Configuration of Django
Involves three basic steps:
Step 1: Install and configure Python

Step 2: Install a Python virtual environment
­  Step 2.1: Open command prompt (cmd) as ‘Administrator’

­  Step 2.2: Plan/ create directory in any of your drive.
­  ­cd C:\MyWorks\Python\Django

­  Step 2.3: Install PIP version. Execute below command in command prompt:
­  python -m pip install –upgrade pip
­  Example: C:\MyWorks\Python\Django>python -m pip install –upgrade pip
­  Step 2.4: Create and install the virtual environment for all the Django projects:
­  py -m pip install virtualenvwrapper-win
­  Example: C:\MyWorks\Python\Django>py -m pip install virtualenvwrapper-win
­­  Step 2.5: Create and install the virtual environment for required projects:
­  mkvirtualenv myproject
­  Example: C:\MyWorks\Python\Django>mkvirtualenv myproject
­  ­Prompt should like ‘(myproject) C:\MyWorks\Python\Django>’
­  Step 2.6: Enter command as ‘workon myproject’
­  ­Generally the system automatically switches to the project environment. If not switched then execute above command.

Step 3: Install and configure Django
­  Step 3.1: Execute ‘py -m pip install Django’
­  Example: (myproject) C:\MyWorks\Python\Django>py -m pip install Django
­  Step 3.2: Create directory for Django projects and go to that directory
­  Example: (myproject) C:\MyWorks\Python\Django>mkdir myProjects
­  Example: (myproject) C:\MyWorks\Python\Django>cd myProjects
­   Step 3.3: 
Verification: django-admin startproject mysite
­  Example: (myproject) C:\MyWorks\Python\Django\myProjects>django-admin startproject mysite
­   Step 3.4: Change project site: cd mysite
­  Step 3.5: Execute: python manage.py migrate. Make sure all are in ok state
­  Step 3.6: Execute: python manage.py runserver. Copy url (http://127.0.0.1:8000/) and paste in browser and test it. If no errors found means installation is successful 🙂


2. Project Structure

1. Any web application project is a collection of different types of files each having its own importance and priority in the applications execution.
2. Majority of the files will be either configuration or integration files which have to be handled properly to their actual directory locations.
3. Django being a framework that supports the web application architecture, it also follows the same principles. As Django maps to the MVC style, design and development has its own project structure.
4. Whenever a new Django project is created, Django creates several files and directories under which the total Django application runs as soon as Django app is started.
5. Django creates its own defaults as soon as the Django project is started which is very common with any Django project.
Example: drive\projects directory\project specific directory….db.sqlite3, manage.py will be standard and one project specific directory will be created.
db.sqlite3: This is the default database created by Django when the user is running the ‘migrate’ command.
manage.py: This is the command line utility for executing the Django commands  within the project.

The main project structure is C:\MyWorks\Python\Django\myProjects\mysite\mysite

project specific directory
1. This directory contains the actual configuration file for every type that exists in the Django application.
2. The main files and directories in the project specific directory are
i. __pycache__
­ i.i. __init__.cpython-37
­  i.ii. settings.cpython-37
­ i.iii. urls.cpython-37
­ i.iv. wsgi.cpython-37
ii. __init__.py : This file is used to initialize the entire application
iii. asgi.py
iv. settings.py
v. urls.py
vi. wsgi.py


3. Creating a new project
Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’. Here myproject is the name of virtual environment which was created in first point. We should see ‘(myproject) C:\MyWorks\Python\Django\myProjects>’
Step 4: Create new project here. Execute ‘django-admin startproject project002’
A new projects directory is created as per the Django structure which was discussed in the second point.
Step 5: Change the directory to new project folder. Execute ‘cd project002’
Step 6: Run the manage.py script to migrate configurations. Execute ‘python manage.py migrate’. All should end with OK. This command is required for dynamic websites and when connecting to database.
Step 7: Starting the Python supplied app templates. Execute ‘python manage.py startapp proj002app’
This step creates a folder called as ‘proj002app’ containing all the required template files structure that is essential to the Django developer. We can use these templates to edit and customise as per project requirement.

To close: command ‘deactivate’ > ‘exit’

For static web pages
Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’. Here myproject is the name of virtual environment which was created in first point. We should see ‘(myproject) C:\MyWorks\Python\Django\myProjects>’
Step 4: Create new project here. Execute ‘django-admin startproject project003’
Step 5: Change the directory to new project folder. Execute ‘cd project003’
Step 6: Inside the ‘project003’ module, check for ‘__init__.py’ file. In this folder create ‘views.py’ file.
Open any text editor (notepad++)  > Enter below code

from django.http import HttpResponse
def myGreetings(request):
    return HttpResponse("Hurray..!!You are getting into the world of Django")

Save the file as ‘views.py’ in the same location where ‘__init__.py’ file resides.

Step 7: Inside the ‘project003’ module, check for ‘urls.py’ file. If the file already exists the open the file in text editor else create new file.
Open ‘urls.py’ file in text editor (notepad++)  > Enter below code

"""project003 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from project003 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.myGreetings)
]

Save the file as ‘urls.py’
Step 8: Run the Django project. Execute ‘python manage.py runserver’. Copy url ‘http://127.0.0.1:8000/’ and check in browser.


4. Running Django application
Run Django web server prior to running Django application. Start Django web server and let it run in the background and then activate the URL for running the Django application.

Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’
Step 4: Change the directory to project folder. Execute ‘cd project003’
Step 5: Run the Django project. Execute ‘python manage.py runserver’. Copy url ‘http://127.0.0.1:8000/’ and check in browser.


5. Login to a new project using notepad++
Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’.

Step 4: Create new project here. Execute ‘django-admin startproject project004’
Step 5: Change the directory to new project folder. Execute ‘cd project004’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’. Go to your directory and verify new folder. ‘C:\MyWorks\Python\Django\myProjects\project004’
Step 7: Notepad++ > View > Project > Project Panel 1 > Right Click on Workspace and save in some folder with some name like DjangoNPWS (Folder path in my machine is ‘C:\MyWorks\Python\Django\DjangoNPWS’). File name can be project004 > Again right click on Workspace and click on ‘Add New Project’ > Rename Project Name to project004 > Save Workspace every time > Right click project004 and click on ‘Add Files from Directory’ > Select your Django project (project004) and click on ok > Making changes to these files will impact only to particular project (project004).
Add this folder to our notepad++ Workspace > Select project004 (below Workspace) > Right click and click ‘Add Files from Directory’ > Select ‘myWebApp’ > Save Workspace
We can make any changes to these files directly from notepad++

Step 8: Open views.py > Enter code as below

from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
def myGreetings(request):
  return HttpResponse("Hi..This is the message coming from myWebApp in Django")

Note: from django.shortcuts import render — Used to load URLDjango view template
myGreetings function returns a response that prints the string onto the screen.

Step 9: Open settings.py file and enter ‘myWebApp’ under INSTALLED_APPS section.

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myWebApp'
]

Step 10: Implementing URL mapping
i) URL mapping refers to the concept of mapping the URL of the view to the Django application.
ii) As per Django URL mapping is done using regular expression and tuples.
iii) Within Django URL mapping is done in the urls.py Python file.

URL Routing: We have to do URL routing to avoid the other unwanted views from getting loaded into the run time application in the browser.
i) Double click to open the ‘urls.py’ file and enter as below

"""project004 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.myGreetings, name = 'myGreetings'),
]

Step 10: Open command prompt (cmd) as ‘Administrator’
Step 11: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 12: Execute ‘workon myproject’
Step 13: Execute ‘cd project004’
Step 14: Execute ‘python manage.py runserver’. Copy url ‘http://127.0.0.1:8000/’ and check in browser.
Step 15: To exit: Ctrl+Fn+B in my dell inspiron laptop

One more example:

Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’.

Step 4: Create new project here. Execute ‘django-admin startproject project005’
Step 5: Change the directory to new project folder. Execute ‘cd project005’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’.
Step 7: Below steps are required for first time
Notepad++ > View > Project > Project Panel 1 > Right Click on Workspace and save in some folder with some name like DjangoNPWS (Folder path in my machine is ‘C:\MyWorks\Python\Django\DjangoNPWS’) — Till here only for first time.
Again right click on Workspace and click on ‘Add New Project’ > Rename Project Name to project005 > Save Workspace every time > Right click project005 and click on ‘Add Files from Directory’ > Select your Django project (project005) and click on ok > Making changes to these files will impact only to particular project (project005)
.
We can make any changes to these files directly from notepad++
Step 8: Open views.py > Enter code as below

from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
def myGreetings(request):
  return HttpResponse(""Hi..We can use html tags inside the views file. <html><body><h1>Make your web-apps easy using Django framework</body></html>")

Step 9: Open settings.py file and enter ‘myWebApp’ under INSTALLED_APPS section.

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myWebApp'
]

Step 10: Open ‘urls.py’ file and enter as below

"""project004 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.myGreetings, name = 'myGreetings'),
]

Step 11: Execute ‘python manage.py runserver’. Copy url ‘http://127.0.0.1:8000/’ and check in browser.
Step 12: To exit: Ctrl+Fn+B in my dell inspiron laptop 🙂


6. Templates
A template is a text file which is generated in text-based format like html, csv, xml and so on.
Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’.

Step 4: Create new project here. Execute ‘django-admin startproject project006’
Step 5: Change the directory to new project folder. Execute ‘cd project006’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’.
Step 7: Notepad++ > File > Open Folder as Workspace… > Select your folder (project006) and click ok >
Step 8: Go to path where your views.py file is located in project006 (C:\MyWorks\Python\Django\myProjects\project006\myWebApp) and create new folder and rename it as ‘templates’.

Step 9: Creating a centralized location for all the templates that should be operated for the project:

i) In the ‘C:\MyWorks\Python\Django\myProjects\project006\myWebApp’ directory create a new directory by name ‘templates’. (C:\MyWorks\Python\Django\myProjects\project006\myWebApp\templates)
ii) This directory will hold all the html pages that are part of the project or Django app
iii) For any web project there is always a methodology of landing with one specific page, which is called as ‘Home’ page. This page is generally names as index.html
iv) Creating index page for the web application ‘index.html’ in the …\templates folder. In notedpad++ enter below code:

<!DOCTYPE html>
<html lang = "en">
<head>
  <meta charset = "UTF-8">
  <title>Index Page</title>
</head>
<body>
  <h1>Hi..Greetings from Srikanth</h1>
  <h2>Make your web-apps easy using Django framework</h2>
</body>

Save as ‘index.html’ inside the templates folder (C:\MyWorks\Python\Django\myProjects\project006\myWebApp\templates)
v) As this templates folder is created by us, Django doesnt has any information about this folder. Hence we should configure Django env to give notice about this folder.
Step 10: Configuring the template folder into Django environment:
i) Open the settings.py file
ii) Enter value under templates and INSTALLED_APPS as below:
‘DIRS’: [os.path.join(BASE_DIR, ‘templates’)],

INSTALLED_APPS = [
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'myWebApp'
]


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',
            ],
        },
    },
]

iii) By default Django templates will look for templates sub directory in each of the INSTALLED_APPS
Step 11: Making the .html file load through the Django views
i) Open views.py and enter code as below

from django.shortcuts import render

# Create your views here.

from django.template import loader
from django.http import HttpResponse

def index(request):
  template = loader.get_template("index.html")
  return HttpResponse(template.render())

Step 12: Implementing the URL routing
i) Open the urls.py and enter code as below

"""project006 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
]

Step 13: Configuring the app to the Django environment
i) Open settings.py file and register the app in the INSTALLED_APPS list

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
  'myWebApp'
]

Step 14: Run the Django server
Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/index’ 🙂


7. Template Variables
Varibales are declared in double flower braces – {{}}
Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject project007’
Step 5: Change the directory to new project folder. Execute ‘cd project007’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’
Step 7: Notepad++ > File > Open Folder as Workspace… > Select your folder (project007) and click ok
Step 8: Create a ‘templates’ directory inside myWebApp directory. Create index.html file under templates directory and enter code as below.

<!DOCTYPE html>
<html lang = "en">
<head>
  <meta charset = "UTF-8">
  <title>Index Page</title>
</head>
<body>
  <h1>Hi..Greetings from Srikanth</h1>
  <h2>Make your web-apps easy using Django framework</h2>
  <h3>{{myGreetings}}</h3>
  <h4>You are connected to my site on :{{calendarDay}}</h4>
</body>

Step 9: Add your app to Django project. Open settings.py file and enter ‘myWebApp’ under INSTALLED_APPS section and under TEMPLATES section add base directory (‘DIRS’: [os.path.join(BASE_DIR, ‘templates’)],)

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myWebApp'
]

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',
            ],
        },
    },
]

Step 10: Open views.py > Enter code as below

from django.shortcuts import render

# Create your views here.

from django.template import loader
from django.http import HttpResponse

from datetime import date
import calendar
import datetime

#use below script in case we have only one variable
#def index(request):
#	currentYear = date.today().year
#	currentYear = int(currentYear)
#	
#	currentMonth = date.today().month
#	currentMonth = int(currentMonth)
#	
#	if currentYear < 1900 or currentYear > 2099: date.today().currentYear
#	
#	monthSpelling = calendar.month_name[currentMonth]
#	myGreetings = "Hi..Django calendar is : %s %s" %(monthSpelling, currentYear)
#	return render(request, 'index.html', {"myGreetings" : myGreetings})
  
#use below script in case we have multiple variables
def index(request):
  template = loader.get_template('index.html') #We are getting our template file here
  currentYear = date.today().year
  currentYear = int(currentYear)
  
  currentMonth = date.today().month
  currentMonth = int(currentMonth)
  
  currentDay = datetime.datetime.now().date()
  
  if currentYear < 1900 or currentYear > 2099: date.today().currentYear
  
  monthSpelling = calendar.month_name[currentMonth]
  myGreetings = "Hi..Django calendar is : %s %s" %(monthSpelling, currentYear)
  myMultiVariable = {
    'myGreetings' : myGreetings,
    'calendarDay' : currentDay
    }
  return HttpResponse(template.render(myMultiVariable))#rendering the template in HttpResponse

Step 11: Open ‘urls.py’ file and enter as below

"""project007 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
]

Step 12: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/index’ 🙂


8. Run existing project
Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’
Step 4: Change the directory to existing project folder. Execute ‘cd project007’
Step 5: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/index’ 🙂


9. Output in table format
Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject project008’
Step 5: Change the directory to new project folder. Execute ‘cd project008’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’
Step 7: Notepad++ > File > Open Folder as Workspace… > Select your folder (project007) and click ok
Step 8: Create a ‘templates’ directory inside myWebApp directory. Create index.html file under templates directory and enter code as below.

<!DOCTYPE html>
<html lang = "en">
<head>
  <meta charset = "UTF-8">
  <title>Students Admission Information</title>
</head>
<body>
  <div style = "width : 50%; margin : 0 auto; font-size : 100%">
    <h1>Students Personal Profile</h1>
    <table border = '1'>
      <tr>
        <th>Student Name</th>
        <td>{{studentName}}</td>
      </tr>
      <tr>
        <th>Student Father Name</th>
        <td>{{studentFatherName}}</td>
      </tr>
      <tr>
        <th>Course Joined</th>
        <td>{{courseJoined}}</td>
      </tr>
      <tr>
        <th>Course Fees</th>
        <td>{{courseFees}}</td>
      </tr>
      <tr>
        <th>Student Address</th>
        <td>{{studentAddress}}</td>
      </tr>
    </table>
    <!--Try below sytnatx as well -->
    <p></p>
    <table border = '1'>
      <tr>
        <th>Student Name</th>
        <th>Student Father Name</th>
        <th>Course Joined</th>
        <th>Course Fees</th>
        <th>Student Address</th>
      </tr>
      <tr>
        <td>{{studentName}}</td>
        <td>{{studentFatherName}}</td>
        <td>{{courseJoined}}</td>
        <td>{{courseFees}}</td>
        <td>{{studentAddress}}</td>
      </tr>
    </table>
  </div>
</body>
</html>

Step 9: Add your app to Django project. Open settings.py file and enter ‘myWebApp’ under INSTALLED_APPS section and under TEMPLATES section add base directory (‘DIRS’: [os.path.join(BASE_DIR, ‘templates’)],)

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myWebApp'
]

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',
            ],
        },
    },
]

Step 10: Open views.py > Enter code as below

from django.shortcuts import render

# Create your views here.

from django.template import loader
from django.http import HttpResponse

def index(request):
  myIndexPage = loader.get_template('index.html')
  myPageData = {
    'studentName' : 'Srikanth',
    'studentFatherName' : 'Shyam',
    'courseJoined' : 'Django',
    'courseFees' : '10,000',
    'studentAddress' : 'B1-816, Amrutha Heights, Marigold Street, Bangalore, Karnataka' 
    }
  return HttpResponse(myIndexPage.render(myPageData, request))

Step 11: Open ‘urls.py’ file and enter as below

"""project008 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
  path('index/', views.index),
]

Step 12: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/index’ 🙂


10. Types of tags used in Django
1. html tags
2. built-in template tags
3. custom template tags

built-in template tags
1. Django provides its own set of built-in tags to implement arbitrary logic within the Django template.
2. Django tags generally have a syntax like {% tag %}, where a Django tag is more complex than the Django variable.
3. Django tags can implement:
i) Creating text in the output
ii) Implement control flow by Conditional statements and Iterative statements
iii) Load external information into the template with the help of the variables.
iv) Provide arbitrary logic in the rendering process.
v) Grab the content from the database
vi) Enable access to other template tags.

Basic syntax: {% tag_name %}
Most of the Django template tags can accept arguments. Syntax will be like {% tag_name ‘argument01’ ‘argument02’ %}

Most commonly used tags are:
1. Comment tag:
{% comment ‘Comment Information’ %}
any commented text can go here
{% endcomment %}
2. Cycle tag (refer to 28 class sometime after 30 mins)
Similar concept of loops.
3. Extends tag (refer to 30 class)
Inherits one page to another page.
4. if tag
5. for loop tag
6. for … empty loop tag (refer to 29 class)
7. firstof Tag (refer to 30 class)
Equal to COALECSE function in Oracle that returns first not null value
8. include tag (refer to 31 class)


11. if tag and if else tag
Syntax: 01
{% if confition %}
­ operation WHEN True
{% endif %}
Syntax: 02
{% if confition %}
­ operation WHEN True
{% else %}
­ operation WHEN False
{% endif %}

Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject project009’
Step 5: Change the directory to new project folder. Execute ‘cd project009’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’
Step 7: Notepad++ > File > Open Folder as Workspace… > Select myProjects folder and click ok
Step 8: Create a ‘templates’ directory inside myWebApp directory. Create index.html file under templates directory and enter code as below.

<!DOCTYPE html>
<html lang = "en">
<head>
  <meta charset = "UTF-8">
  <title>Index</title>
</head>
<body>
  <h1>Illustration of simple IF tag in Django templates</h1>
  {% if givenValue %}
    <p>The variable is passed with a value</p>
    <p>The value in the variable is : {{givenValue}}</p>
  {% endif %}
  <p>Printing details of level 1</p>
  <p>Printing details of level 2</p>
  <p>Printing details of level 3</p>
</body>
</html>

Step 9: Open settings.py file and enter ‘myWebApp’ under INSTALLED_APPS section and under TEMPLATES section add base directory (‘DIRS’: [os.path.join(BASE_DIR, ‘templates’)],)

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
  'myWebApp'
]
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',
            ],
        },
    },
]

Step 10: Open views.py > Enter code as below. Try executing by replacing value 10 with None then if condition will fails.

from django.shortcuts import render

# Create your views here.

from django.template import loader
from django.http import HttpResponse

def index(request):
  myIndexPage = loader.get_template('index.html')
  valueScanned = {"givenValue" : 10}
  return HttpResponse(myIndexPage.render(valueScanned, request))

Step 11: Open ‘urls.py’ file and enter as below

"""project009 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
  path('index/', views.index),
]

Step 12: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/index’ 🙂

Example with else keyword
Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject project010’
Step 5: Change the directory to new project folder. Execute ‘cd project010’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’
Step 7: Notepad++ > File > Open Folder as Workspace… > Select myProjects folder and click ok
Step 8: Create a ‘templates’ directory inside myWebApp directory. Create index.html file under templates directory and enter code as below.

<!DOCTYPE html>
<html lang = "en">
<head>
  <meta charset = "UTF-8">
  <title>Index</title>
</head>
<body>
  <h1>Illustration of simple IF tag in Django templates</h1>
  {% if givenValue %}
    <p>The variable is passed with a value</p>
    <p>The value in the variable is : {{givenValue}}</p>
  {% else %}
    <p>The variable is not passed with a value</p>
    <p>The value in the variable is : {{givenValue}}</p>
    <p>Missing data cannot process further</p>
  {% endif %}
  <p>Printing details of level 1</p>
  <p>Printing details of level 2</p>
  <p>Printing details of level 3</p>
</body>
</html>

Step 9: Open settings.py file and enter ‘myWebApp’ under INSTALLED_APPS section and under TEMPLATES section add base directory (‘DIRS’: [os.path.join(BASE_DIR, ‘templates’)],)

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
  'myWebApp'
]
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',
            ],
        },
    },
]

Step 10: Open views.py > Enter code as below. Try executing by replacing value 10 with None then if condition will fails.

from django.shortcuts import render

# Create your views here.

from django.template import loader
from django.http import HttpResponse

def index(request):
  myIndexPage = loader.get_template('index.html')
  valueScanned = {"givenValue" : None}
  return HttpResponse(myIndexPage.render(valueScanned, request))

Step 11: Open ‘urls.py’ file and enter as below

"""project010 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
  path('index/', views.index),
]

Step 12: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/index’ 🙂

One more example with else keyword
Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject project011’
Step 5: Change the directory to new project folder. Execute ‘cd project011’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’
Step 7: Notepad++ > File > Open Folder as Workspace… > Select myProjects folder and click ok
Step 8: Create a ‘templates’ directory inside myWebApp directory. Create index.html file under templates directory and enter code as below.

<!DOCTYPE html>
<html lang = "en">
<head>
  <meta charset = "UTF-8">
  <title>Index</title>
</head>
<body>
  <div style = "width:50%; margin:0 auto; font-size:150%">
    <h1>Illustration of simple if else tag in Django templates</h1>
    {% if foodieType == 'vegan' %}
    <h3>The food type choosen is : Vegetraian</h3>
    <p align="left"; style="font-family:arial; color:#008000;"><b>The advantages of being vegetaian are: </b></p>
      <ul>
        <li>Advantage 1</li>
        <li>Advantage 2</li>
        <li>Advantage 3</li>
      </ul>
    {% else %}
    <h3>The food type choosen is : Non-Vegetraian</h3>
    <p align="left"; style="font-family:arial; color:#FF0000;"><b>The advantages of being non-vegetaian are: </b></p>
      <ul>
        <li>Advantage 1</li>
        <li>Advantage 2</li>
        <li>Advantage 3</li>
      </ul>
    {% endif %}
  </div>
</body>
</html>

Step 9: Open settings.py file and enter ‘myWebApp’ under INSTALLED_APPS section and under TEMPLATES section add base directory (‘DIRS’: [os.path.join(BASE_DIR, ‘templates’)],)

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myWebApp'
]
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',
            ],
        },
    },
]

Step 10: Open views.py > Enter code as below.

from django.shortcuts import render

# Create your views here.
from django.template import loader
from django.http import HttpResponse

def index(request):
  myIndexPage = loader.get_template('index.html')
  valueScanned = {"foodieType" : 'non-vegan'}
  return HttpResponse(myIndexPage.render(valueScanned, request))

Step 11: Open ‘urls.py’ file and enter as below

"""project011 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
  path('index/', views.index),
]

Step 12: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/index’ 🙂


12. for tag
1. Used to loop through a sequence type of objects
2. The sequence type can be i) Python Lists ii) Python Tupes iii) Python Dictionaries

Syntax:

{% for loopIndex in sequenceType %}
     all operations on the extracted element from the sequence type
{% endfor %}

Example:

Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject project012’
Step 5: Change the directory to new project folder. Execute ‘cd project012’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’
Step 7: Notepad++ > File > Open Folder as Workspace… > Select myProjects folder and click ok
Step 8: Create a ‘templates’ directory inside myWebApp directory. Create index.html file under templates directory and enter code as below.

<!DOCTYPE html>
<html lang = "en">
  <head>
    <meta charset = "UTF-8">
    <title>Index</title>
  </head>
  <body>
    <h1>Welcome to the number management using "for" tag</h1>
    <p>The list used for picking the numbers is : {{ listName }}</p>
    <h4>The extracted numbers from the list are...</h4>
    <ul>
      {% for loopIndex in myNumList %}
        <li>{{ loopIndex }}</li>
      {% endfor %}
    </ul>
  </body>
</html>

Step 9: Open settings.py file and enter ‘myWebApp’ under INSTALLED_APPS section and under TEMPLATES section add base directory (‘DIRS’: [os.path.join(BASE_DIR, ‘templates’)],)

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myWebApp'
]
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',
            ],
        },
    },
]

Step 10: Open views.py > Enter code as below.

from django.shortcuts import render

# Create your views here.
from django.template import loader
from django.http import HttpResponse

def index(request):
  myIndexPage = loader.get_template('index.html')
  myNumListDictinary = {
    "listName" : "myNumList",
    "myNumList" : [10, 20, 30, 40, 50, 60, 70, 80, 90]
    }
  return HttpResponse(myIndexPage.render(myNumListDictinary, request))

Step 11: Open ‘urls.py’ file and enter as below

"""project012 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
  path('index/', views.index),
]

Step 12: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/index’ 🙂


13. Internal Hyperlinks
Let us build a web application having three pages
i) Landing page: Home page or Index page
ii) About us page
iii) More information page

Hyperlinks in HTML
1. Hyper links are also called as html links
2. Hyper links are used to click and navigate to another web page or another document.
3. When a mouse pointer is placed on the hyper link the pointer turns to a little hand icon.
4. Hyper links can be text based or image based or html element.

Syntax: <a href = “URL”>Link Text</a>

Types of hyper links:
1. Local links or intra page links: Link to the same page or within the same website.
2. Image links: Will make any image on website behave like a html link. We have to specify the image source.
3. Button links: Will make form based buttons to act as html links. They generally have an event associated to it, integrated with some dynamic script like Java Script

Target attribute  in html links:
1. Used to specify where to open the actual link document.
2. Can take any one of the four attributes.
i) _blank : Opens the target document in a new window or tab
ii) _self:  Opens the target document in a same window or tab. This is default link
iii) _parent: Opens the target document in a parent frame
iv) _top: Opens the target document in the full body of the window
Syntax: <a href = “URL” target = “attribute”>Link Text</a>
Note: Replace attribute with any four above discussed attributes.

Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject project013’
Step 5: Change the directory to new project folder. Execute ‘cd project013’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’
Step 7: Notepad++ > File > Open Folder as Workspace… > Select myProjects folder and click ok
Step 8: Create a ‘templates’ directory inside myWebApp directory. Create three .html files under templates directory and enter code as below.

homePage.html

<!DOCTYPE html>
<html lang = "en">
  <head>
    <meta charset = "UTF-8">
    <title>Home Page</title>
  </head>
  <body>
    <h1>Home page of website</h1>
    <p>This web site has following pages
      <ol>
        <li>The first page is the home information page</li>
        <li>The second page is the about us information page</li>
        <li>The third page is the more information page</li>
      </ol>
    </p>
    <a href = "{% url 'aboutPage' %}">Go to About Page</a>
  </body>
</html>

aboutUs.html

<!DOCTYPE html>
<html lang = "en">
  <head>
    <meta charset = "UTF-8">
    <title>About us Page</title>
  </head>
  <body>
    <h1>About us page of website</h1>
    <p>About us information page speaks about the company
      <ol>
        <li>First line in about us page</li>
        <li>Second line in about us page</li>
        <li>Third line in about us page</li>
      </ol>
    </p>
    <a href = "{% url 'homePage' %}">Go to Home Page</a>
    <a href = "{% url 'moreInfoPage' %}">Go to More Information Page</a>
  </body>
</html>

moreInfo.html

<!DOCTYPE html>
<html lang = "en">
  <head>
    <meta charset = "UTF-8">
    <title>More Information Page</title>
  </head>
  <body>
    <h1>More infomation page of website</h1>
    <p>More information page gives more details about the company
      <ol>
        <li>First line in more infomation page</li>
        <li>Second line in more infomation page</li>
        <li>Third line in more infomation page</li>
      </ol>
    </p>
    <a href = "{% url 'aboutPage' %}">Go to About Page</a>
    <a href = "{% url 'homePage' %}">Go to Home Page</a>
  </body>
</html>

Step 9: Open settings.py file and enter ‘myWebApp’ under INSTALLED_APPS section and under TEMPLATES section add base directory (‘DIRS’: [os.path.join(BASE_DIR, ‘templates’)],)

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myWebApp'
]
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',
            ],
        },
    },
]

Step 10: Open views.py > Enter code as below.

from django.shortcuts import render

# Create your views here.
from django.template import loader
from django.http import HttpResponse

def homePage(request):
  return render(request, 'homePage.html', {})
  
def aboutPage(request):
  return render(request, 'aboutUs.html', {})
  
def moreInfoPage(request):
  return render(request, 'moreInfo.html', {})

Step 11: Open ‘urls.py’ file and enter as below

"""project013 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
  path('homePage/', views.homePage, name = 'homePage'),
  path('aboutPage/', views.aboutPage, name = 'aboutPage'),
  path('moreInfoPage/', views.moreInfoPage, name = 'moreInfoPage'),
]

Step 12: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/homePage’ 🙂


14. External Hyperlinks

Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject project014’
Step 5: Change the directory to new project folder. Execute ‘cd project014’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’
Step 7: Notepad++ > File > Open Folder as Workspace… > Select myProjects folder and click ok
Step 8: Create a ‘templates’ directory inside myWebApp directory. Create three .html files under templates directory and enter code as below.

homePage.html

<!DOCTYPE html>
<html lang = "en">
  <head>
    <meta charset = "UTF-8">
    <title>Home Page</title>
  </head>
  <body>
    <h1>Home page of website</h1>
    <p>This web site has following pages
      <ol>
        <li>The first page is the home information page</li>
        <li>The second page is the about us information page</li>
        <li>The third page is the more information page</li>
      </ol>
    </p>
    <a href = "{% url 'aboutPage' %}">Go to About Page</a>
  </body>
</html>

aboutUs.html

<!DOCTYPE html>
<html lang = "en">
  <head>
    <meta charset = "UTF-8">
    <title>About us Page</title>
  </head>
  <body>
    <h1>About us page of website</h1>
    <p>About us information page speaks about the company
      <ol>
        <li>First line in about us page</li>
        <li>Second line in about us page</li>
        <li>Third line in about us page</li>
      </ol>
    </p>
    
    <div>
      <h3>Web sites you can visit from my website</h3>
      <p>Click on the link to open a website...</p>
      <a href = "https://www.oracle.com" target = "_blank">Oracle Corporation</a>
      <br>
      <br>
      <a href = "https://www.microsoft.com">Microsoft Corporation</a>
      <br>
      <br>
      <a href = "https://www.nasa.gov/">Nasa Space Research</a>
    </div>
    <br>
    <br>
    <a href = "{% url 'homePage' %}">Go to Home Page</a>
    <a href = "{% url 'moreInfoPage' %}">Go to More Information Page</a>
  </body>
</html>

moreInfo.html

<!DOCTYPE html>
<html lang = "en">
  <head>
    <meta charset = "UTF-8">
    <title>More Information Page</title>
  </head>
  <body>
    <h1>More infomation page of website</h1>
    <p>More information page gives more details about the company
      <ol>
        <li>First line in more infomation page</li>
        <li>Second line in more infomation page</li>
        <li>Third line in more infomation page</li>
      </ol>
    </p>
    <a href = "{% url 'aboutPage' %}">Go to About Page</a>
    <a href = "{% url 'homePage' %}">Go to Home Page</a>
  </body>
</html>

Step 9: Open settings.py file and enter ‘myWebApp’ under INSTALLED_APPS section and under TEMPLATES section add base directory (‘DIRS’: [os.path.join(BASE_DIR, ‘templates’)],)

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myWebApp'
]
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',
            ],
        },
    },
]

Step 10: Open views.py > Enter code as below.

from django.shortcuts import render

# Create your views here.
from django.template import loader
from django.http import HttpResponse

def homePage(request):
  return render(request, 'homePage.html', {})
  
def aboutPage(request):
  return render(request, 'aboutUs.html', {})
  
def moreInfoPage(request):
  return render(request, 'moreInfo.html', {})

Step 11: Open ‘urls.py’ file and enter as below

"""project014 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
  path('homePage/', views.homePage, name = 'homePage'),
  path('aboutPage/', views.aboutPage, name = 'aboutPage'),
  path('moreInfoPage/', views.moreInfoPage, name = 'moreInfoPage'),
]

Step 12: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/homePage’ 🙂


15. Dynamic Loading of Web Pages

Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject project015’
Step 5: Change the directory to new project folder. Execute ‘cd project015’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’
Step 7: Notepad++ > File > Open Folder as Workspace… > Select myProjects folder and click ok
Step 8: Create a ‘templates’ directory inside myWebApp directory. Create three .html files under templates directory and enter code as below.

homePage.html

<!DOCTYPE html>
<html lang = "en">
  <head>
    <meta charset = "UTF-8">
    <title>Home Page</title>
  </head>
  <body>
    <h1>Home page of website</h1>
    <p>This web site has following pages
      <ol>
        <li>The first page is the home information page</li>
        <li>The second page is the about us information page</li>
        <li>The third page is the more information page</li>
      </ol>
    </p>
    <a href = "{% url 'aboutUs' %}">Go to About Page</a>
  </body>
</html>

aboutUs.html

<!DOCTYPE html>
<html lang = "en">
  <head>
    <meta charset = "UTF-8">
    <title>About us Page</title>
  </head>
  <body>
    <h1>About us page of website</h1>
    <p>About us information page speaks about the company</p>
      <ol>
        <li>First line in about us page</li>
        <li>Second line in about us page</li>
        <li>Third line in about us page</li>
      </ol>


    <div>
      <h3>Web sites you can visit from my website</h3>
      <p>Click on the link to open a website...</p>
        {% for webSitesListIndex in webSitesList %}
          {% if '.html' in webSitesListIndex.webLink %}
            <p>
              <a href = "{% url webSitesListIndex.webLink|slice:":-5" %}"> {{ webSitesListIndex.webSiteName | lower }} </a>
            </p>
          {% else %}
            <p>
              <a href = "{{ webSitesListIndex.webLink }}" target=_self" {{ webSitesListIndex.webSiteName }} </a>
            </p>
          {% endif %}
        {% endfor %}
    </div>
    <br>
    <br>
    <a href = "{% url 'homePage' %}">Go to Home Page</a>
  </body>
</html>

moreInfo.html

<!DOCTYPE html>
<html lang = "en">
  <head>
    <meta charset = "UTF-8">
    <title>More Information Page</title>
  </head>
  <body>
    <h1>More infomation page of website</h1>
    <p>More information page gives more details about the company
      <ol>
        <li>First line in more infomation page</li>
        <li>Second line in more infomation page</li>
        <li>Third line in more infomation page</li>
      </ol>
    </p>
    <a href = "{% url 'aboutUs' %}">Go to About Page</a>
    <a href = "{% url 'homePage' %}">Go to Home Page</a>
  </body>
</html>

Step 9: Open settings.py file and enter ‘myWebApp’ under INSTALLED_APPS section and under TEMPLATES section add base directory ‘DIRS’: [os.path.join(BASE_DIR, ‘myWebApp/templates’)],

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myWebApp'
]
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'myWebApp/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',
            ],
        },
    },
]

Step 10: Open views.py > Enter code as below.

from django.shortcuts import render

# Create your views here.
from django.views.generic import TemplateView

def homePage(request):
    return render(request, 'homePage.html', {})

webSitesDataList = [
    {'webSiteName' : 'Oracle.com', 'webLink' : 'https://www.oracle.com'},
    {'webSiteName' : 'Microsoft.com', 'webLink' : 'https://www.microsoft.com'},
    {'webSiteName' : 'Nasa.gov', 'webLink' : 'https://www.nasa.gov'},
    {'webSiteName' : 'Web Radio', 'webLink' : 'http://radio.garden'},
    {'webSiteName' : 'More information...', 'webLink' : 'moreInfo.html'},
]

def aboutUs(request):
    webLinksContext = {'webSitesList' : webSitesDataList}
    return render(request, 'aboutUs.html', webLinksContext)

class MorePageView(TemplateView):
    template_name = "moreInfo.html"

def moreInfoPage(request):
    return render(request, 'moreInfo.html', {})

Step 11: Open ‘urls.py’ file and enter as below

"""project015 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.conf.urls import include
from django.contrib import admin
from django.urls import path, re_path

urlpatterns = [
    # path(r'^admin/', admin.site.urls),
    re_path(r'^(?P<admin>[0-9])/', admin.site.urls),
    path('', include('myWebApp.urls'))
]

Create ‘urls.py’ under myWebApp directory and provide as below:

from django.conf.urls import  url
from django.urls import path
from . import views

urlpatterns = [
    path('homePage/', views.homePage, name = 'homePage'),
    path('aboutUs/', views.aboutUs, name = 'aboutUs'),
    path('moreInfo/', views.MorePageView.as_view(), name = 'moreInfo'),
]

Step 12: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/homePage’ 🙁
The website links are not appearing..25 n 26


16. Images/ Audio files in web page

We can load images, audio files, video files, documents (word, ppt, excel)

Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject project016’
Step 5: Change the directory to new project folder. Execute ‘cd project016’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’
Step 7: Notepad++ > File > Open Folder as Workspace… > Select myProjects folder and click ok
Step 8: Create a ‘static’ directory inside myWebApp directory.
Create a ‘images’ directory inside static directory. Place any png or jpg image file inside images directory.
Create a ‘audio’ directory inside static directory. Place any mp3 file inside audio directory.
Create a ‘video’ directory inside static directory. Place any mp4 file inside video directory.
Create a ‘templates’ directory inside myWebApp directory. Create a index.html file under templates directory and enter code as below.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Display image in Django</title>
</head>
<body>
<h1>First Image</h1>
{% load static %}
<img src ="{% static 'images/1.jpg' %}" alt="Nani First Image"/>
<br>
<p>Image using Django</p>
<br>
<br>
<br>
<br>
<h1>One of my fav song...</h1>
{% load static %}
<audio controls>
    <source src ="{% static 'audio/Nani.m4a' %}" type = "audio/m4a">
    Your browser does not support the audio element.
</audio>
<br>
<br>
<br>
<br>
<h1>Video tag...</h1>
{% load static %}
<video width = "70%" width "100% controls autoplay>
<source src ="{% static 'videos/Nani.mp4' %}" type = "video/mp4"></body></source>
</video>
</body>
</html>

Step 9: Open settings.py file and enter ‘myWebApp’ under INSTALLED_APPS section and under TEMPLATES section add base directory ‘DIRS’: [os.path.join(BASE_DIR, ‘myWebApp/templates’)],

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myWebApp'
]
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'myWebApp/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',
            ],
        },
    },
]

Step 10: Open views.py > Enter code as below.

from django.shortcuts import render

# Create your views here.
from django.template import loader
from django.http import HttpResponse

def index(request):
    return render(request, 'index.html')

Step 11: Open ‘urls.py’ file and enter as below

"""project016 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
]

Step 12: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/homePage’ 🙂


17. Comment tag

Syntax:
{% comment ‘Comment Information’ %}
any commented text can go here
{% endcomment %}

Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject project017’
Step 5: Change the directory to new project folder. Execute ‘cd project017’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’
Step 7: Notepad++ > File > Open Folder as Workspace… > Select myProjects folder and click ok
Step 8: Create a ‘templates’ directory inside myWebApp directory. Create a index.html file under templates directory and enter code as below.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Comments Tag in Django</title>
</head>
<body>
    <h1>Comment Tags in Django</h1>
    <p><b>Example to display comments tag in Django</b></p>
    <br>
    <br>
    <h3> Displaying the data that is uncommented...</h3>
    {{ headerForDisplay }}
    <br>
    {{ paraForDisplay }}
    <br>
    <h3>Illustration of the commented tag in Django...</h3>
    {% comment "Information in the comment section" %}
    <br>
    {{ commentedText }}
    <br>
    {% endcomment %}
</body>
</html>

Step 9: Open settings.py file and enter ‘myWebApp’ under INSTALLED_APPS section and under TEMPLATES section add base directory ‘DIRS’: [os.path.join(BASE_DIR, ‘myWebApp/templates’)],

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myWebApp'
]
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'myWebApp/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',
            ],
        },
    },
]

Step 10: Open views.py > Enter code as below.

from django.shortcuts import render

# Create your views here.
def index(request) :
    dataList = {
        "headerForDisplay" : "<h1> Comments tag in Django</h1>",
        "paraForDisplay" : "<p> Example of para to display</p>",
        "commentedTex" : "Commented text in Django"
    }
    return render(request, "index.html", dataList)

Step 11: Open ‘urls.py’ file and enter as below

"""project017 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
]

Step 12: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/homePage’ 🙂


18. Django Forms

Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject project018’
Step 5: Change the directory to new project folder. Execute ‘cd project018’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’
Step 7: Notepad++ > File > Open Folder as Workspace… > Select myProjects folder and click ok
Step 8: settings.py – Changes are highlighted below

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myWebApp'
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'myWebApp/templates')],

Step 9: forms.py – Create forms.py file under myWebApp folder

from django import forms

class DepartmentsForm(forms.Form) :
    departmentID = forms.DecimalField(label="Enter Department ID")
    departmentName = forms.CharField(label="Enter Department Name")
    departmentLocation = forms.CharField(label="Enter Department Location")

Step 10: index.html – myWebApp folder > Create templates folder > Create index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Index</title>
</head>
<body>
<form method="POST" class="post-form">
    {% csrf_token %}
    {{ form.as_p }}
    <button type ="submit" class="save btn btn-default">Save</button>
</form>
</body>
</html>

Step 11: views.py

from django.shortcuts import render

# Create your views here.
from myWebApp.forms import DepartmentsForm

def index(request) :
    deptInfo = DepartmentsForm()
    return render(request, "index.html", {'form':deptInfo})

Step 12: urls.py

from django.contrib import admin
from django.urls import path
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
]

Step 13: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/index/’ 🙂


19. Form Field Elements

Form Element Name Form Element Class Syntax Remarks Reference HTML Element
BooleanField class BooleanField(**kwargs) fieldName = forms.BooleanField(**options) It is a check box field which is used to store True or False state CheckboxInput
CharField class CharField(**kwargs) fieldName = forms.CharField(**options) It is a string field, supporting small or large size string data TextInput
ChoiceField class ChoiceField(**kwargs) fieldName = forms.ChoiceField(**options) It is a string field which is used to select a particular element out of the list of available values. In general also called as drop down list or pop list Select
TypedChoiceField class TypeChoicedField(**kwargs) fieldName = forms.TypeChoicedFieldField(**options) It is a string field which is used to select a particular element out of the list of available values and by requirement we can even enter the values. In general also called as drop down list or combo list. Select
DateField class DateField(**kwargs)

fieldName = forms.DateField(**options)

Acceptable formats:
1. %Y-%m-%d : 2020-05-01
2. %m/%d/%Y : 05/01/2020
3. %m/%d/%y : 05/01/20

It is date field used to take date inputs from the end user DateInput
DateTimeField class DateTimeField(**kwargs)

fieldName = forms.DateTimeField(**options)

Acceptable formats:
1. %Y-%m-%d %H:%M:%S : 2020-05-01 08:43:25

It is date field used to take date and time inputs from the end user DateTimeInput
DecimalField class DecimalField(**kwargs) fieldName = forms.DecimalField(**options) It is defined to take input NumberInput
DurationField class DurationField(**kwargs) fieldName = forms.DurationField(**options) It is a field that takes text input but the data in the form of durations TextInput
EmailField class EmailField(**kwargs) fieldName = forms.EmailField(**options) It is a field that takes string input with format applied for emails EmailInput
FileField class FileField(**kwargs) fieldName = forms.FileField(**options) It is a field that is used for uploading of files ClearableFileInput
FilePathField class FilePathField(**kwargs) fieldName = forms.FilePathField(**options) It is a string based file to cross verify the path of the file on the server Select
FloatField class FloatField(**kwargs) fieldName = forms.FloatField(**options) It is a integer field for accepting the floating point numbers from the end user NumberInput
ImageField class ImageField(**kwargs) fieldName = forms.ImageField(**options) It is an input field for uploading Image files ClearableFileInput
IntegerField class IntegerField(**kwargs) fieldName = forms.IntegerField(**options) It is an input field for accepting the integer numbers from the end user NumberInput
GenericIPAddressField class GenericIPAddressField(**kwargs) fieldName = forms.GenericIPAddressField(**options) It is text field for accepting the IP addresses TextInput
MultipleChoiceField class MultipleChoiceField(**kwargs) fieldName = forms.MultipleChoiceField(**options) It is a string field which is used to select multiple elements out of the list of available values SelectMultiple
TypedMultipleChoiceField class TypedMultipleChoiceField(**kwargs) fieldName = forms.TypedMultipleChoiceField(**options) It is a string field which is used to select multiple elements out of the list of available values. Also it is enterable and Editable SelectMultiple
NullBooleanField class NullBooleanField(**kwargs) fieldName = forms.NullBooleanField(**options) It is a select field which stored true or false state NullBooleanSelect
RegexField class RegexField(**kwargs) fieldName = forms.RegexField(**options) It is a text field for supporting the search facility TextInput
SlugField class SlugField(**kwargs) fieldName = forms.SlugField(**options) It is a field for short labels. Can accept only characters, numbers, underscores and hyphen TextInput
TimeField class TimeField(**kwargs) fieldName = forms.TimeField(**options) It is field for managing the input of only the time element TextInput
URLField class URLField(**kwargs) fieldName = forms.URLField(**options) It is a field for managing the URL inputs URLInput
UUIDField class UUIDField(**kwargs) fieldName = forms.UUIDField(**options) It is field for managing unique values as input TextInput

20. Feedback Form

Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject project019’
Step 5: Change the directory to new project folder. Execute ‘cd project019’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’
Step 7: Notepad++ > File > Open Folder as Workspace… > Select myProjects folder and click ok
Step 8: settings.py – Changes are highlighted below

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myWebApp'
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'myWebApp/templates')],

Step 9: forms.py – Create forms.py file under myWebApp folder

from django import forms

class FeedBackForm(forms.Form) :
    feedBackUserName = forms.CharField(label='Enter Your Name', max_length=100)
    feedBackUserEmail = forms.EmailField(label='Enter Your Email', max_length=100)
    feedBackUserMobile = forms.CharField(label='Enter Your Mobile Number', max_length=100)
    feedBackData1 = forms.CharField(label='Enter Your Feedback1', max_length=1000)
    feedBackData2 = forms.CharField(label='Enter Your Feedback2', widget=forms.Textarea(attrs={'width' : "100%", 'cols' : "80", 'rows' : "20",}))

Step 10: feedBackForm.html
myWebApp folder > Create templates folder > Create feedBackForm.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Feedback Form</title>
</head>
<body>
<h2>Please provide your valuable feedback</h2>
<form>
    {% csrf_token %}
    <!--Uncomment below to check different styles-->
    <!--
    {{ form }}
    -->
    <!--
    {{ form.as_ul }}
    -->
    <!--
    {{ form.as_p }}
    -->

    <table>
     {{ form.as_table }}
    </table>
    
    <input type ="submit" value = "Submit" />
</form>
</body>
</html>

Step 11: views.py

from django.shortcuts import render

# Create your views here.
from myWebApp.forms import FeedBackForm

def feedBackForm(request) :
    feedBackFormObj = FeedBackForm()
    return render(request, "feedBackForm.html", {'form':feedBackFormObj})

Step 12: urls.py

from django.contrib import admin
from django.urls import path
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('feedBackForm/', views.feedBackForm),
]

Step 13: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/feedBackForm/’ 🙂


21. Redirection of feedback form to new form

Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject project020’
Step 5: Change the directory to new project folder. Execute ‘cd project020’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’
Step 7: Notepad++ > File > Open Folder as Workspace… > Select myProjects folder and click ok
Step 8: settings.py – Changes are highlighted below

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myWebApp'
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'myWebApp/templates')],

Step 9: forms.py – Create forms.py file under myWebApp folder

from django import forms

class FeedBackForm(forms.Form) :
    feedBackUserName = forms.CharField(label='Enter Your Name', max_length=100)
    feedBackUserEmail = forms.EmailField(label='Enter Your Email', max_length=100)
    feedBackUserMobile = forms.CharField(label='Enter Your Mobile Number', max_length=100)
    feedBackData = forms.CharField(label='Enter Your Feedback', widget=forms.Textarea(attrs={'width' : "100%", 'cols' : "80", 'rows' : "20",}))

Step 10: feedBackForm.html
myWebApp folder > Create templates folder > Create feedBackForm.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Feedback Form</title>
</head>
<body>
<h2>Please provide your valuable feedback</h2>
    <form action = "/thankYouFeedBack/" method="post">
        {% csrf_token %}
        <table>
         {{ form.as_table }}
        </table>
        <input type ="submit" value = "Submit" />
    </form>
</body>
</html>

Step 11: thankYouFeedBack.html
myWebApp folder > Create templates folder > Create thankYouFeedBack.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Thank you for your feedback</title>
</head>
<body>
    <h2>Your feeback is received as : </h2>
    <form method="post">
        <ul>
            <li>Your name received is : <strong>{{ feedBackUserName }}</strong></li>
            <li>Your registered email is : <strong>{{ feedBackUserEmail }}</strong></li>
            <li>Your registered mobile is : <strong>{{ feedBackUserMobile }}</strong></li>
            <li>Your valuable feedback is : <strong>{{ feedBackData }}</strong></li>
        </ul>
    </form>
</body>
</html>

Step 12: views.py

from django.shortcuts import render

# Create your views here.
from myWebApp.forms import FeedBackForm
from django.template import loader
from django.http import HttpResponse

def feedBackForm(request) :
    if request.method == 'POST' :
        feedBackFormObj = FeedBackForm(request.POST)
        if feedBackFormObj.is_valid() :
            feedBackUserName = feedBackFormObj.cleaned_data['feedBackUserName']
            feedBackUserEmail = feedBackFormObj.cleaned_data['feedBackUserEmail']
            feedBackUserMobile = feedBackFormObj.cleaned_data['feedBackUserMobile']
            feedBackData = feedBackFormObj.cleaned_data['feedBackData']

            context = {
                'feedBackUserName' : feedBackUserName,
                'feedBackUserEmail' : feedBackUserEmail,
                'feedBackUserMobile' : feedBackUserMobile,
                'feedBackData' : feedBackData
                }
            template = loader.get_template('thankYouFeedBack.html')
            return HttpResponse(template.render(context, request))
    else :
        feedBackFormObj = FeedBackForm()

        return render(request, 'feedBackForm.html', {'form' : feedBackFormObj})

Step 13: urls.py
Navigation: project020 > urls.py

from django.contrib import admin
from django.urls import path, include
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myWebApp.urls')),
]

Step 14: urls.py
Navigation: myWebApp > urls.py

from django.contrib import admin
from django.urls import path
from myWebApp import views as myWebApp_view

urlpatterns = [
    path('admin/', admin.site.urls),
    path('feedBackForm/', myWebApp_view.feedBackForm),
    path('thankYouFeedBack/', myWebApp_view.feedBackForm),
]

Step 15: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/feedBackForm/’ 🙂


22. Employee Form

Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject project021’
Step 5: Change the directory to new project folder. Execute ‘cd project021’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’
Step 7: Notepad++ > File > Open Folder as Workspace… > Select myProjects folder and click ok
Step 8: settings.py – Changes are highlighted below

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myWebApp'
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'myWebApp/templates')],

Step 9: forms.py – Create forms.py file under myWebApp folder

from django import forms


class EmployeesForm(forms.Form) :
    employeeID = forms.DecimalField(label="Enter Employee ID", max_digits=4, min_value=1, max_value=1000, required=True, initial=1, help_text="Please enter Employee Number")
    employeeName = forms.CharField(label="Enter Employee Name", max_length=50, required=True, initial="Employee Name")
    employeeJob = forms.CharField(label="Enter Employee Designation", max_length=50, required=True, initial="Job", help_text="Please enter Employee Designation")
    employeeHireDate = forms.DateField(label="Enter Employee Joining Date", required=True, help_text="Please enter Employee Joining Date")
    employeeSalary = forms.DecimalField(label="Enter Employee Salary", max_digits=10, required=True, help_text="Please enter Employee Salary")
    employeeCommission = forms.DecimalField(label="Enter Employee Commission", max_digits=10, required=False, help_text="Please enter Employee Commission")
    employeeManagerID = forms.DecimalField(label="Enter Employee Manager ID", max_digits=10, required=False, help_text="Please enter Employees Manager ID")
    employeeDepartmentID = forms.DecimalField(label="Enter Employee Department ID", max_digits=10, required=True, help_text="Please enter Employee Department ID")

Step 10: index.html
myWebApp folder > Create templates folder > Create index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Index</title>
</head>
<body>
    <form method = "POST" class = "post-form">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="save btn btn-default">Save</button>
    </form>
</body>
</html>

Step 11: views.py

from django.shortcuts import render
from myWebApp.forms import EmployeesForm

# Create your views here.
def index(request) :
    empInfo = EmployeesForm()
    return render(request, "index.html", {'form' : empInfo})

Step 12: urls.py

from django.contrib import admin
from django.urls import path
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
]

Step 13: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/index/’ 🙂


23. Employee Form with Choice Field and redirection to new form

Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject project022’
Step 5: Change the directory to new project folder. Execute ‘cd project022’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’
Step 7: Notepad++ > File > Open Folder as Workspace… > Select myProjects folder and click ok
Step 8: settings.py – Changes are below

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myWebApp'
]

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

Step 9: forms.py – Create forms.py file under myWebApp folder

from django import forms

EMPLOYEE_DESIGNATIONS = (
    ("P", "PRESIDENT"),
    ("M", "MANAGER"),
    ("A", "ANALYST"),
    ("S", "SALESMAN"),
    ("C", "CLERK"),
)


class EmployeesForm(forms.Form) :
    employeeID = forms.DecimalField(label="Enter Employee ID", max_digits=4, min_value=1, max_value=1000, required=True, initial=1)
    employeeName = forms.CharField(label="Enter Employee Name", max_length=50, required=True, initial="Employee Name")
    employeeJob = forms.ChoiceField(label="Select Employee Designation", required=True, initial="Select the Job", choices=EMPLOYEE_DESIGNATIONS)
    employeeHireDate = forms.DateField(label="Enter Employee Joining Date", required=True, initial="2020-01-25")
    employeeSalary = forms.DecimalField(label="Enter Employee Salary", max_digits=10, required=True)
    employeeCommission = forms.DecimalField(label="Enter Employee Commission", max_digits=10, required=False)
    employeeManagerID = forms.DecimalField(label="Enter Employee Manager ID", max_digits=10, required=False)
    employeeDepartmentID = forms.DecimalField(label="Enter Employee Department ID", max_digits=10, required=True)

Step 10: employeesForm.html
myWebApp folder > Create templates folder > Create employeesForm.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Employees Form</title>
</head>
<body>
<h2>Please enter the employees data</h2>
    <form action = "/employeesFormData/" method="post">
        {% csrf_token %}
        <table>
         {{ form.as_table }}
        </table>
        <input type ="submit" value = "Submit" />
    </form>
</body>
</html>

Step 11: employeesFormData.html
myWebApp folder > Create templates folder > Create employeesFormData.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Employee Registration Form</title>
</head>
<body>
    <h2>The details of employee record is : </h2>
    <form method="post">
        <ul>
            <li>Employee ID : <strong>{{ employeeID }}</strong></li>
            <li>Employee Name : <strong>{{ employeeName }}</strong></li>
            <li>Employee Job : <strong>{{ employeeJob }}</strong></li>
            <li>Employee HireDate : <strong>{{ employeeHireDate }}</strong></li>
            <li>Employee Salary : <strong>{{ employeeSalary }}</strong></li>
            <li>Employee Commission : <strong>{{ employeeCommission }}</strong></li>
            <li>Employee Manager ID : <strong>{{ employeeManagerID }}</strong></li>
            <li>Employee Department ID : <strong>{{ employeeDepartmentID }}</strong></li>
        </ul>
    </form>
</body>
</html>

Step 12: views.py

from django.shortcuts import render

# Create your views here.
from myWebApp.forms import EmployeesForm
from django.template import loader
from django.http import HttpResponse

def employeesForm(request) :
    if request.method == 'POST' :
        employeesFormObj = EmployeesForm(request.POST)
        if employeesFormObj.is_valid() :
            employeeID = employeesFormObj.cleaned_data['employeeID']
            employeeName = employeesFormObj.cleaned_data['employeeName']
            employeeJob = employeesFormObj.cleaned_data['employeeJob']
            employeeHireDate = employeesFormObj.cleaned_data['employeeHireDate']
            employeeSalary = employeesFormObj.cleaned_data['employeeSalary']
            employeeCommission = employeesFormObj.cleaned_data['employeeCommission']
            employeeManagerID = employeesFormObj.cleaned_data['employeeManagerID']
            employeeDepartmentID = employeesFormObj.cleaned_data['employeeDepartmentID']

            context = {
                'employeeID' : employeeID,
                'employeeName' : employeeName,
                'employeeJob' : employeeJob,
                'employeeHireDate' : employeeHireDate,
                'employeeSalary': employeeSalary,
                'employeeCommission': employeeCommission,
                'employeeManagerID': employeeManagerID,
                'employeeDepartmentID': employeeDepartmentID
                }
            template = loader.get_template('employeesFormData.html')
            return HttpResponse(template.render(context, request))
    else :
        employeesFormObj = EmployeesForm()

        return render(request, 'employeesForm.html', {'form' : employeesFormObj})

Step 13: urls.py
Navigation: project022 > urls.py

from django.contrib import admin
from django.urls import path, include
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myWebApp.urls')),
]

Step 14: urls.py
Navigation: myWebApp > urls.py

from django.contrib import admin
from django.urls import path
from myWebApp import views as myWebApp_view

urlpatterns = [
    path('admin/', admin.site.urls),
    path('employeesForm/', myWebApp_view.employeesForm),
    path('employeesFormData/', myWebApp_view.employeesForm),
]

Step 15: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/employeesForm/’ 🙂


24. Multiple Choice Fields

Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject project023’
Step 5: Change the directory to new project folder. Execute ‘cd project023’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’
Step 7: Notepad++ > File > Open Folder as Workspace… > Select myProjects folder and click ok
Step 8: settings.py – Changes are below

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myWebApp'
]

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

Step 9: forms.py – Create forms.py file under myWebApp folder

from django import forms

EMPLOYEE_DESIGNATIONS = (
    ("PRESIDENT", "PRESIDENT"),
    ("MANAGER", "MANAGER"),
    ("ANALYST", "ANALYST"),
    ("SALESMAN", "SALESMAN"),
    ("CLERK", "CLERK")
)

EMPLOYEE_SKILLS = (
    ("C-Lang", "C-Lang"),
    ("Java", "Java"),
    ("HTML", "HTML"),
    ("Hadoop", "Hadoop"),
    ("Python", "Python")
)


class EmployeesForm(forms.Form) :
    employeeID = forms.DecimalField(label="Employee ID", max_digits=4, min_value=1, max_value=1000, required=True, initial=1)
    employeeName = forms.CharField(label="Employee Name", max_length=50, required=True, widget=forms.TextInput(attrs={'placeholder': 'Emp Name'}))
    employeeGender = forms.BooleanField(label="Check for Male", required=False,)
    employeeJob = forms.ChoiceField(label="Select Employee Designation", required=True, initial="Select the Job", choices=EMPLOYEE_DESIGNATIONS)
    employeeSkills = forms.MultipleChoiceField(label="Select Employee Skills", required=True, initial="Select the Skills", choices=EMPLOYEE_SKILLS)
    employeeHireDate = forms.DateField(label="Employee Joining Date", required=True, widget=forms.SelectDateWidget)
    employeeSalary = forms.DecimalField(label="Employee Salary", max_digits=10, required=True, widget=forms.TextInput(attrs={'placeholder': 'Emp Salary'}))
    employeeCommission = forms.DecimalField(label="Employee Commission", max_digits=10, required=False, widget=forms.TextInput(attrs={'placeholder': 'Emp Commission'}))
    employeeManagerID = forms.DecimalField(label="Employee Manager ID", max_digits=10, required=False, widget=forms.TextInput(attrs={'placeholder': 'Emp Manager ID'}))
    employeeDepartmentID = forms.DecimalField(label="Employee Department ID", max_digits=10, required=True, widget=forms.TextInput(attrs={'placeholder': 'Emp Dept ID'}))

 

Step 10: employeesForm.html
myWebApp folder > Create templates folder > Create employeesForm.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Employees Form</title>
</head>
<body>
<h2>Please enter the employees data</h2>
    <form action = "/employeesFormData/" method="post">
        {% csrf_token %}
        <table>
         {{ form.as_table }}
        </table>
        <input type ="submit" value = "Submit" />
    </form>
</body>
</html>

Step 11: employeesFormData.html
myWebApp folder > Create templates folder > Create employeesFormData.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Employee Registration Form</title>
</head>
<body>
    <h2>The details of employee record is : </h2>
    <form method="post">
        <ul>
            <li>Employee ID : <strong>{{ employeeID }}</strong></li>
            <li>Employee Name : <strong>{{ employeeName }}</strong></li>
            <li>Employee Gender : <strong>{{ employeeGender }}</strong></li>
            <li>Employee Job : <strong>{{ employeeJob }}</strong></li>
            <li>Employee Skills : <strong>{{ employeeSkills }}</strong></li>
            <li>Employee HireDate : <strong>{{ employeeHireDate }}</strong></li>
            <li>Employee Salary : <strong>{{ employeeSalary }}</strong></li>
            <li>Employee Commission : <strong>{{ employeeCommission }}</strong></li>
            <li>Employee Manager ID : <strong>{{ employeeManagerID }}</strong></li>
            <li>Employee Department ID : <strong>{{ employeeDepartmentID }}</strong></li>
        </ul>
    </form>
</body>
</html>

Step 12: views.py

from django.shortcuts import render

# Create your views here.
from myWebApp.forms import EmployeesForm
from django.template import loader
from django.http import HttpResponse

def employeesForm(request) :
    if request.method == 'POST' :
        employeesFormObj = EmployeesForm(request.POST)
        if employeesFormObj.is_valid() :
            employeeID = employeesFormObj.cleaned_data['employeeID']
            employeeName = employeesFormObj.cleaned_data['employeeName']
            employeeGender = employeesFormObj.cleaned_data['employeeGender']
            employeeJob = employeesFormObj.cleaned_data['employeeJob']
            employeeSkills = employeesFormObj.cleaned_data['employeeSkills']
            employeeHireDate = employeesFormObj.cleaned_data['employeeHireDate']
            employeeSalary = employeesFormObj.cleaned_data['employeeSalary']
            employeeCommission = employeesFormObj.cleaned_data['employeeCommission']
            employeeManagerID = employeesFormObj.cleaned_data['employeeManagerID']
            employeeDepartmentID = employeesFormObj.cleaned_data['employeeDepartmentID']

            if employeeGender == True :
                displayGender = "Male"
            else :
                displayGender = "Female"

            context = {
                'employeeID' : employeeID,
                'employeeName' : employeeName,
                'employeeGender': displayGender,
                'employeeJob' : employeeJob,
                'employeeSkills': employeeSkills,
                'employeeHireDate' : employeeHireDate,
                'employeeSalary': employeeSalary,
                'employeeCommission': employeeCommission,
                'employeeManagerID': employeeManagerID,
                'employeeDepartmentID': employeeDepartmentID
                }
            template = loader.get_template('employeesFormData.html')
            return HttpResponse(template.render(context, request))
    else :
        employeesFormObj = EmployeesForm()

        return render(request, 'employeesForm.html', {'form' : employeesFormObj})

Step 13: urls.py
Navigation: project023 > urls.py

from django.contrib import admin
from django.urls import path, include
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myWebApp.urls')),
]

Step 14: urls.py
Navigation: myWebApp > urls.py

from django.contrib import admin
from django.urls import path
from myWebApp import views as myWebApp_view

urlpatterns = [
    path('admin/', admin.site.urls),
    path('employeesForm/', myWebApp_view.employeesForm),
    path('employeesFormData/', myWebApp_view.employeesForm),
]

Step 15: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/employeesForm/’ 🙂


25. SQLite Installation

Step 1: https://sqlitebrowser.org/dl/
Step 2: DB Browser for SQLite – Standard installer for 64-bit Windows


26. Model Field Elements

Serial No. Model Field or Attribute Form Field or Attribute
1. AutoField This field is generally used as primary key in the database for auto generating the primary key values.Hence this field is not represented in the form
2. SmallAutoField This field is generally used as primary key in the database for auto generating the primary key values.Hence this field is not represented in the form
3. BigAutoField This field is generally used as primary key in the database for auto generating the primary key values.Hence this field is not represented in the form
4. BigIntegerField This field is used to store very large integer values with “min_value : -9223372036854775808” and “max_value : 9223372036854775807”. This is represented in the form as IntegerField
5. IntegerField Represented in the form as IntegerField
6. PositiveIntegerField Represented in the form as IntegerField
7. PositiveSmallIntegerField Represented in the form as IntegerField
8. DecimalField This field is preferred when we have to store the data as floating point values including precision and scale. Represented in the form as DecimalField
9. FloatField This field is preferred when we have to store the data as floating point values including precision and scale. Represented in the form as FloatField
10. CharField CharField when set with “max_length” will reference to the “max_length” of the form and it is automatically set to “none” will make “null = True”
11. TextField CharField field applied with widget as widget = forms.Textarea
12. DateField DateField
13. DateTimeField DateTimeField
14. DurationField DurationField
15. TimeField TimeField
16. BooleanField or NullBooleanField BooleanField or NullBooleanField when null=True
 17. BinaryField CharField only when the editable property is set to “True” on the model else it is not represented in the form
18. EmailField EmailField
19. FileField FileField
20. FilePathField FilePathField
21. IPAddressField IPAddressField
22. GenericIPAddressField GenericIPAddressField
23. URLField URLField
24. SlugField SlugField
25. ForeignKey ModelChoiceField
26. ManyToMany ModelMultipleChoiceField

27. Department Model Form

Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject project024’
Step 5: Change the directory to new project folder. Execute ‘cd project024’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’
Step 7: Run the ‘manage.py’ file to synchronise the default database SQLLite in DJango. Make sure to run this command where manage.py exists. Execute ‘python manage.py migrate –run-syncdb’
Step 8: settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myWebApp'
]

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

Step 9: models.py

from django.db import models

# Create your models here.

class DeptModel(models.Model) :
    deptID = models.PositiveSmallIntegerField()
    deptName = models.CharField(max_length=50)
    deptLoc = models.CharField(max_length=20)
    class Meta :
        db_table = "deptinfo"

Step 10: forms.py – Create forms.py file under myWebApp folder

from django import forms
from myWebApp.models import DeptModel


class DeptModelForm(forms.ModelForm):
    class Meta:
        model = DeptModel
        fields = "__all__"

Step 11: deptInfo.html
myWebApp folder > Create templates folder > Create deptInfo.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Model Form Illustration</title>
</head>
    <body>
    <form method="POST" class="post-form">
        {% csrf_token %}
        {{ form.as_p }}
        <button type = "submit" class="save btn btn-default">Save</button>
    </form>
    </body>
</html>

Step 12: views.py

from django.shortcuts import render
from myWebApp.forms import DeptModelForm

# Create your views here.
def deptInfo(request) :
    deptFormObj = DeptModelForm()
    return render(request, "deptInfo.html", {'form' : deptFormObj})

Step 13: urls.py

from django.contrib import admin
from django.urls import path
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('deptInfo/', views.deptInfo)
]

Step 14: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/deptInfo/’ 🙂


28. Employee Model Form

Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject project025’
Step 5: Change the directory to new project folder. Execute ‘cd project025’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’
Step 7: settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myWebApp'
]

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

Step 8: models.py

from django.db import models
import datetime


# Create your models here.

class EmpModel(models.Model):
    empID = models.PositiveSmallIntegerField(verbose_name="Employee ID")
    empName = models.CharField(max_length=50, verbose_name="Employee Name")
    empJob = models.CharField(max_length=20, verbose_name="Employee Job")
    empHireDate = models.DateField(default=datetime.date.today(), verbose_name="Employee Hire Date")
    empMGRID = models.PositiveSmallIntegerField(verbose_name="Employee Manager ID")
    empBasicSal = models.DecimalField(max_digits=7, decimal_places=2, verbose_name="Employee Basic Salary")
    empComm = models.DecimalField(max_digits=7, decimal_places=2, verbose_name="Employee Commission")
    empDeptID = models.PositiveSmallIntegerField(verbose_name="Employee Department ID")

    class Meta:
        db_table = "empinfo"

Step 9: forms.py – Create forms.py file under myWebApp folder

from django import forms
from myWebApp.models import EmpModel


class EmpModelForm(forms.ModelForm):
    class Meta:
        model = EmpModel
        fields = "__all__"
        ##In case we want to see few fields then use below syntax
        ##fields = ['empID', 'empName', 'empJob']

Step 10: empInfo.html
myWebApp folder > Create templates folder > Create empInfo.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Model Form Illustration</title>
</head>
    <body>
    <form method="POST" class="post-form">
        {% csrf_token %}
        <table>
            {{ form.as_table }}
            <tr>
             <td>&nbsp;</td>
            </tr>
        </table>
        <button type = "submit" class="save btn btn-default">Save</button>
    </form>
    </body>
</html>

Step 11: views.py

from django.shortcuts import render
from myWebApp.forms import EmpModelForm


# Create your views here.
def empInfo(request):
    empFormObj = EmpModelForm()
    return render(request, "empInfo.html", {'form': empFormObj})

Step 12: urls.py

from django.contrib import admin
from django.urls import path
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('empInfo/', views.empInfo)
]

Step 13: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/empInfo/’ 🙂


29. CSS/ Bootstrap

Including the default boot strap CSS reference into DJango project
1. We can include the default CSS files created by the boot strap framework directly into DJango
2. In the .html files where we want to add the CSS, include in the <head> tag the required boot strap reference stylesheet using the <link> tag.

<head>
    <meta charset="UTF-8">
    <title>CSS</title>
  <link rel="stylesheet" href="//maxcdn.bootstarpcdn.com/bootstarp/3.2.0/css/bootstarp.min.css">
  <link rel="stylesheet" href="//maxcdn.bootstarpcdn.com/bootstarp/3.2.0/css/bootstarp-theme.min.css">
</head>

Including our custom CSS files into the DJango projects
1. To add our own customized CSS files we have to create the corresponding CSS files in the ‘static’ folder of the current webapp that is being developed.
2. By adding the CSS files as static files the applications content doesnt depends on the request context and it will be the same for every user who is accessing the DJango web application.
3. DJango by default has the basic knowledge to find and run the static files for the built-in ‘admin’ app.
4. Create a folder by name ‘static’ in the actual webapp that is being created in the DJango application and keep the CSS files registered in this folder.
5. Whenever the DJango application is run, it definitely searched for the ‘static’ folder in the app and then executes all the static files that have been configured to the DJango application.
6. One webapp can contain any number of CSS files kept under one directory representing all the CSS standards for that project.
7. Once the CSS files are created they should be saved with .css extension in the statis folder under CSS sub-directory.

Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject project026’
Step 5: Change the directory to new project folder. Execute ‘cd project026’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’
Step 7: settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myWebApp'
]

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

Step 8: myCSS.css
myWebApp folder > Create static folder > Create css folder > Create myCSS.css file

h2 a, h3 a {
    color : #EF6216;
}

Step 9: index.html
myWebApp folder > Create templates folder > Create index.html

<!DOCTYPE html>

{% load static %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Index</title>
    <link rel="stylesheet" href="//maxcdn.bootstarpcdn.com/bootstarp/3.2.0/css/bootstarp.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstarpcdn.com/bootstarp/3.2.0/css/bootstarp-theme.min.css">
    <link rel="stylesheet" href="{% static 'css/myCSS.css' %}">
</head>
<body>
<div>
    <h2><a href="/">Departments Information Form</a></h2>
    <p>This form will display the information of the departments that can be added to the application with respect to
        our organization</p>
    <form method="POST" class="post-form">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="save btn btn-default">Save</button>
    </form>
    <h3><a href="/">End of departments information</a></h3>
    <p>The end user once enters the data in this form will save the data into the database for further reference</p>
</div>
</body>
</html>

Step 10: forms.py – Create forms.py file under myWebApp folder

from django import forms


class DepartmentsForm(forms.Form):
    departmentID = forms.DecimalField(label="Enter Department ID")
    departmentName = forms.CharField(label="Enter Department Name")
    departmentLocation = forms.CharField(label="Enter Department Location")

Step 11: views.py

from django.shortcuts import render

# Create your views here.
from myWebApp.forms import DepartmentsForm


def index(request):
    deptInfo = DepartmentsForm()
    return render(request, "index.html", {'form': deptInfo})

Step 12: urls.py

from django.contrib import admin
from django.urls import path
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
]

Step 13: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/index’ 🙂


30. CSS for table format output

Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject project027’
Step 5: Change the directory to new project folder. Execute ‘cd project027’
Step 6: Execute in command prompt ‘django-admin startapp myWebApp’
Step 7: Notepad++ > File > Open Folder as Workspace… > Select your folder (project007) and click ok
Step 8: settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myWebApp'
]

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

Step 9: Create a ‘templates’ directory inside myWebApp directory. Create index.html file under templates directory and enter code as below.

<!DOCTYPE html>

{% load static %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Students Admission Information</title>
    <link rel="stylesheet" href="//maxcdn.bootstarpcdn.com/bootstarp/3.2.0/css/bootstarp.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstarpcdn.com/bootstarp/3.2.0/css/bootstarp-theme.min.css">
    <link rel="stylesheet" href="{% static 'css/myCSS.css' %}">
</head>
<body>
<div style="width : 50%; margin : 0 auto; font-size : 100%">
    <h1>Students Personal Profile</h1>
    <table border='1'>
        <tr>
            <th>Student Name</th>
            <td>{{studentName}}</td>
        </tr>
        <tr>
            <th>Student Father Name</th>
            <td>{{studentFatherName}}</td>
        </tr>
        <tr>
            <th>Course Joined</th>
            <td>{{courseJoined}}</td>
        </tr>
        <tr>
            <th>Course Fees</th>
            <td>{{courseFees}}</td>
        </tr>
        <tr>
            <th>Student Address</th>
            <td>{{studentAddress}}</td>
        </tr>
    </table>
    <!--Try below sytnatx as well -->
    <p></p>
    <table border='1'>
        <tr>
            <th>Student Name</th>
            <th>Student Father Name</th>
            <th>Course Joined</th>
            <th>Course Fees</th>
            <th>Student Address</th>
        </tr>
        <tr>
            <td>{{studentName}}</td>
            <td>{{studentFatherName}}</td>
            <td>{{courseJoined}}</td>
            <td>{{courseFees}}</td>
            <td>{{studentAddress}}</td>
        </tr>
    </table>
</div>
</body>
</html>

Step 9: myCSS.css
myWebApp folder > Create static folder > Create css folder > Create myCSS.css file

.page-header {
    background-color : #C25100
    margin-top : 0;
    padding : 20px 20px 20px 40px;
}

.page-header h1, .page-header h1 a, .page-header h1 a : visited, .page-header h1 a : active {
    color : #ffffff;
    font-size : 36pt;
    text-decoration : none;
}

.content {
    margin-left : 40px;
}

h1, h2, h3, h4 {
    font-family : 'Lobster', cursive;
}

.date {
    color : #828282
}

.save {
    float : right;
}

.post-form textarea, .post-form input {
    width : 100%;
}

.top-menu, .top-menu : hover, .top-menu : visited {
    color : #ffffff;
    float : right;
    font-size : 26pt;
    margin-right : 20px;
}

.post {
    margin-bottom : 70px;
}

.post h2 a, .post h2 a : visited {
    color : #000000;
}

Step 10: Open views.py > Enter code as below

from django.shortcuts import render

# Create your views here.

from django.template import loader
from django.http import HttpResponse

def index(request):
  myIndexPage = loader.get_template('index.html')
  myPageData = {
    'studentName' : 'Srikanth',
    'studentFatherName' : 'Shyam',
    'courseJoined' : 'Django',
    'courseFees' : '10,000',
    'studentAddress' : 'B1-816, Amrutha Heights, Marigold Street, Bangalore, Karnataka' 
    }
  return HttpResponse(myIndexPage.render(myPageData, request))

Step 11: Open ‘urls.py’ file and enter as below

from django.contrib import admin
from django.urls import path
from myWebApp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
]

Step 12: Run the Django server. Execute: python manage.py runserver. Copy url and enter in browser as ‘http://127.0.0.1:8000/index’ 🙁


31. Primary and Foreign Key concepts in DJango

Primary key concepts in DJango
1. DJango framework provides the facility to manage the ‘Primary Key’ within the DJango Models.
2. DJango Models has built-in field validations which are default validations that are shipped pre-defined to all DJango fields.
3. Every DJango field in the model will be applied with the built-in validations with the help of DJango validators.
4. The developers by requirement can add more built-in field validations for applying or eliminating certain constraints with specific to a particular field as per the demand of the situation.
5. To apply a primary key in DJango model we should set the ‘primary_key = True’ property upon the field that is considered as primary key by analysis.
6. When the developer is not defining the property of ‘primary_key = True’ for any of the existing fields in the model then DJango will automatically add an ‘AutoField’ to hold the primary key.
7. When should set ‘primary_key = True’ on any of the fields that are declared in the model only when we want to override the default primary key behaviour provided by DJango.
8. ‘primary_key = True’ will automatically implies
i) null = False
ii) unique = True
9. Within the model that is being designed we can have only one primary key by declaration to the object that is being created out of the model class.
Syntax: modelFieldName = models.Field(primary_key = True)

Basic Illustration

from django.db import models

#Create your models here.

class DeptModel(models.Model) : 
deptID = models.PositiveSmallIntegerField(primary_key = True)
deptName = models.CharField(max_length = 20)
deptLoc = models.CharField(max_length = 20)
class Meta : 
db_table = "deptinfo"

Foreign Key Concepts in DJango
1. DJango models represent the exact constructs that are supported by RDBMS
2. When models are created using DJango we can apply the relations that are specified in the data model or ER diagram.
3. According to DJango there are three types of relational fields.
i) Many-To-One
ii) Many-To-Many
iii) One-To-One


32. DJango Project 01

Step 01: Planning and designing the Models
Before we start coding for the DJango Models, we have to analyze
i. What kind of data we are intending to store into the database.
ii. The relationships between the different DJango Python Objects(Models).

Model 01: Departments
1. This will store all the departments that are registered in the organization.
2. Each department is uniquely identified by its ‘Department ID’.
Attributes:
i. Department ID: DeptID
ii. Department Name: DeptName
iii. Department Location: DeptLoc

Model 02: Employees
1. This will store all the employees working in the organization.
2. Each employee is uniquely identified by its ‘Employee ID’.
Attributes:
i. Employee ID: EmpID
ii. Employee Name: EmpName
iii. Job Category ID: JobCatID
iv. Hired Date: HireDate
v. Basic Salary: EmpSal
vi. Commission: EmpComm
vii. Manager ID: EmpMGRID
viii. Department ID: EmpDeptID

Model 03: Employees Deputations
1. This will store all the employees deputation information.
2. Each employee deputation will have its unique ‘Deputation ID’.
Attributes:
i. Deputation ID: DeputID
ii. Deputation Date:DeputDate
iii. Deputation Period: DeputPeriod
iv. Deputation Status: DeputStatus
v. Deputation City: DeputCity

Model 04: Job Category
1. This will store all the job categories information.
2. The different job categories are identified by the application with unique job category.
Attributes:
i. Job Category ID: JobCatID
ii. Job Category Name:JobCatName
iii. Job Category Description: JobCatDesc

Model 05: Skills
1. This will store all the skills information.
2. The different skills are identified by the application with unique skill.
Attributes:
i. Skill ID: SkillID
ii. Skill Name:SkillName
iii. Skill Description: SkillDesc

Step 02: Planning Model Relationships
1. Once all the models are ready, then plan the relationships between the models as per the ‘relation state’ and ‘relation cardinality’
2. DJango allows to define the relationships as:
i. One-to-one
ii. One-to-many(Foreign Keys)
iii. Many-to-many

Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’

Step 4: Create new project here. Execute ‘django-admin startproject hrmsmgmt’
Step 5: Change the directory to new project folder. Execute ‘cd hrmsmgmt’
Step 6: Execute in command prompt ‘python manage.py startapp hrmscatalog’
Step 7: settings.py

<<settings.py>>

Creating the required Models for the application:
1. Identify the actual DJango app in which models are essential: C:\MyWorks\Python\Django\myProjects\hrmsmgmt\hrmscatalog\models.py
2. Open the models.py in the editor and add the code for the models in the order of primary key models first followed by foreign key.

<<models.py>>

Note:
1. Once the basic models are ready with the first level with which the application development can be initiated, we can load these initial models into the database.
2. Whenever we make additions or changes to the models in th DJango environment we have to execute migrations such that the changes in the models are applied upon the database in the backend.

Step 03: Creating the admin dashboard for the project

Note:
1. For every DJango application it has its own DJango administration dash board.
2. Admin dashboard is the place where all the components of the DJango application are centralized and can be accessed.

Steps to follow:
1. Connect to command prompt in the OS level.
Open command prompt (cmd) as ‘Administrator’
2. Change the directory where the project is placed.
Execute ‘cd C:\MyWorks\Python\Django\myProjects’
3. Activate the virtual environment. Execute ‘workon myproject’
4. Change to the application directory where manage.py file is available. Execute ‘cd hrmsmgmt’
5. If the application directory is already created previously then just run the migrations. ‘python manage.py makemigrations’
If executed successfully all the models in the framework are ready to get mapped to the model forms and database tables.
6. Migrate models to database ‘python manage.py migrate’
If executed successfully all the models in the framework are migrated to the as database tables and these tables are kept in synchronized mapping to the models in the DJango framework. Whenever there is a change in the DJango models due to enchancements or change requests or maintenance. Once the changes in the DJango model framework in completed then we should be run the step 5 and step 6.
7. Run the DJango application server to launch the application server in the back ground. ‘python manage.py runserver’
In browser open – http://127.0.0.1:8000/admin
8. Keep running the server (above step) and open another instance of command promt and change to the DJango application directory activating the virtual environment. ‘(myproject) C:\MyWorks\Python\Django\myProjects\hrmsmgmt>’. Create super user ‘python manage.py createsuperuser’
Username: gdsrikanth
email address: gdsrikanth@gmail.com
password: gdsrikanth
by pass validation
9. In http://127.0.0.1:8000/admin give your username and password and we should be able to login.

10. For re-login just run the server.
cd C:\MyWorks\Python\Django\myProjects
workon myproject
cd hrmsmgmt
python manage.py runserver
http://127.0.0.1:8000/admin

11. Registering the models as tables into database.
admin.py file

<<admin.py>>

12. Whenever we make changes to the Model re-run below scripts:
cd C:\MyWorks\Python\Django\myProjects
workon myproject
cd hrmsmgmt
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
http://127.0.0.1:8000/admin

13. Handling the migration error issues
Method 01: Remove the migration files and drop the database but this is not recommendable method due to DB drop
1. Navigate to the migrations folder of the corresponding DJango app.
2. Remove all the files in the migrations directory except ‘__inti__.py’ and ‘__pycache__’ directory.
3. Drop the current database or delete the ‘db.sqlite3’
4. Create the initial migrations once again and generate the database schema.
‘python manage.py makemigrations’
‘python manage.py migrate’

Method 02: Remove the current migrations and keep the existing database
1. Confirm the models that are created are exactly fitting to the current DB.
2. Execute and try to create new migrations.
‘python manage.py makemigrations’
Note: If any pending migrations are existing then apply those migrations first, till we see messgae – no changes detected.
3. Clear the previous migration history from the corresponding DJango app.
i) To see the track of previous migrate execute ‘python manage.py showmigrations’.
ii) After the migrations track history is displayed then clear the migrations history. ‘python manage.py migrate –fake <appname> zero’
iii) Confirm the migrations status ‘python manage.py showmigrations’
4. Remove all the files in the migrations directory except ‘__inti__.py’ and ‘__pycache__’ directory.
Confirm the migrations status ‘python manage.py showmigrations’
5. Create the initial migrations once again
‘python manage.py makemigrations’
6. Apply or fake the migration process as initial migration as the DB is already existing
‘python manage.py migrate –fake-initial’
Confirm the migrations status ‘python manage.py showmigrations’

cd C:\MyWorks\Python\Django\myProjects
workon myproject
cd hrmsmgmt
python manage.py makemigrations
python manage.py showmigrations
python manage.py migrate --fake hrmscatalog zero
python manage.py showmigrations
python manage.py migrate
python manage.py runserver
http://127.0.0.1:8000/admin

 

 


33. DJango Project 02 – Password Generator

Step 1: Open command prompt (cmd) as ‘Administrator’
Step 2: Execute ‘cd C:\MyWorks\Python\Django\myProjects’
Step 3: Execute ‘workon myproject’
Step 4: Create new project here. Execute ‘django-admin startproject password_generator’
Step 5: Change the directory to new project folder. Execute ‘cd password_generator’
Step 6: Execute: ‘python manage.py migrate’. Make sure all are in ok state
Step 7: Execute in command prompt ‘django-admin startapp generator’
Step 8: settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'generator',
]

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

Step 9: Create a ‘templates’ directory inside generator directory. Create index.html and password.html files under templates directory and enter code as below.

<!DOCTYPE html>
<html lang = "en">
<head>
  <meta charset = "UTF-8">
  <title>Index Page</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
    <div class="container text-center">
        <h1>Password Generator</h1>
        <form action="password">
            <select name="length">
                <option value="6">6</option>
                <option value="7">7</option>
                <option value="8">8</option>
                <option value="9" selected="selected">9</option>
                <option value="10">10</option>
                <option value="11">11</option>
                <option value="12">12</option>
                <option value="13">13</option>
                <option value="14">14</option>
            </select> Length
        <br>
        <input type="checkbox" name="uppercase"> Uppercase
        <br>
        <input type="checkbox" name="lowercase"> Lowercase
        <br>
        <input type="checkbox" name="number"> Numbers
        <br>
        <input type="checkbox" name="special"> Special Characters
        <br>
        <input type="submit" value="Generate Password" class="btn btn-primary">
        </form>
    </div>
</body>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Password</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
    <div class="container text-center">
    <h1>Your Password is</h1>
    <h2 class="alert alert-success">{{ password }}</h2>
    <br>
    <a href="{% url 'index' %}" class="btn btn-info">Home</a>
    </div>
</body>
</html>

Step 10: views.py

from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse
import random


# Create your views here.

def index(request):
    template = loader.get_template("index.html")
    return HttpResponse(template.render())


def password(request):
    characters = list('abcdefghijklmnopqrstuvwxyz')

    if request.GET.get('uppercase'):
        characters.extend(list('ABCDEFGHIJKLMNOPQRSTUVWXYZ'))

    if request.GET.get('lowercase'):
        characters.extend(list('abcdefghijklmnopqrstuvwxyz'))

    if request.GET.get('number'):
        characters.extend(list('0123456789'))

    if request.GET.get('special'):
        characters.extend(list('!@#$%^&*()'))

    len = int(request.GET.get('length'))

    thepassword = ''
    for x in range(len):
        thepassword += random.choice(characters)

    return render(request, 'password.html', {'password': thepassword})

Step 11: urls.py

from django.contrib import admin
from django.urls import path
from generator import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),
    path('password/', views.password),
]

Step 12: Execute ‘python manage.py runserver’. Copy url (http://127.0.0.1:8000/) and paste in browser and test it. If no errors found means installation is successful. Alternatively we can use url as localhost:8000 where 127.0.0.1 = localhost and 8000 is port number. 🙂


colorpicker.com
divtable.com
html-css-js.com