Monday, January 26, 2026

Python 39

Models

What is a model? (in ORM)

A model is a python class that represents a table in the database 

 One model = one database table 

 One object = one row in that table 

Instead of directly connecting to the database and writing inline sql queries 

What is Sqlalchemy?

Student table structure 

Task1: without ORM 

Step1: Create isolated environment

PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day39> python -m venv ccitenv

Step2:Activate

PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day39> ccitenv/Scripts/activate 

(ccitenv) PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day39> 

Step3: Install mysql

(ccitenv) PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day39> pip install pymysql

Collecting pymysql

  Using cached pymysql-1.1.2-py3-none-any.whl.metadata (4.3 kB)

Using cached pymysql-1.1.2-py3-none-any.whl (45 kB)

Installing collected packages: pymysql

Successfully installed pymysql-1.1.2

[notice] A new release of pip is available: 25.2 -> 25.3

[notice] To update, run: python.exe -m pip install --upgrade pip

Step4: 

app.py

import pymysql

Connection =pymysql.connect(
    host='localhost',
    user='root',
    password='root',
    port=3306,
    database='ccitdb'
)
cursor=Connection.cursor()
cursor.execute("Insert into students (name, email,mobile) values ('John Doe', 'john@example.com', '1234567890')")
Connection.commit()
print(cursor.rowcount, "Data inserted successfully")
cursor.close()


Output: Mysql 1 records insert successfully in students table

(ccitenv) PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day39> python app.py

1 Data inserted successfully


Task2: With ORM 

Step1:

ORM(Object Relation mapping)

ORM is a technique that allow us to interact with a database using objects and classes instead of writing SQL queries.

Why ORM is needed 

Database understand SQL, but applications are written in object-oriented programming language like python or java 

  •  Object-oriented language
  •  Relational database 

Without ORM :Above example given 

With ORM : Not required write SQL queries, need to write model

  • Models

What is a Model?(in ORM)

A Model is  a python class that represents a table in the database

One model = One database table 

One Object =One row in that table 

Database   ORM

Table        Model(class)

ROW       Object

COLUMN Class attribute

SQL          Python code 

CREATE TABLE `students` (

  `id` int NOT NULL AUTO_INCREMENT,

  `name` varchar(45) DEFAULT NULL,

  `email` varchar(45) DEFAULT NULL,

  `mobile` varchar(45) DEFAULT NULL,

  PRIMARY KEY (`id`)

Student model (ORM/Python):

Class student:

 Id = integer

name =string 

Email =string

mobile =string

Instead of directly connecting to the database and writing inline queries ,we can use models to communicate with the database .This make code simpler, cleaner and easier to maintain.

For that we can use SQL Alchemy library

  • SQL Alchemy

What is SQL Alchemy?

SQLAlchemy is a python library used to communicate with relational database(MYSQL,PostgreSQL,SQLlite,Oracle) using Python code  instead of raw SQL.

It acts as a bridge between python and databases.

In one line: SQLAlchemy lets you work with  database using python objects instead of writing sql queries.

Why Do we need SQLAlchemy?

Database Understand SQL

Applications are written in Python

SQLAlchemy connects both

(it will not support Complex queries),We can write stored procedure and calls 

It helps you: 

 Avoid writing raw Sql

write clean, readable python code

Safely interact with database

SQLAlchemy -->ORM Logic 

Mysql--->Mysql Driver 

MYSQL-->Database engine

Task3: With ORM 

Step1:Install SQLAlchemy 

(ccitenv) PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day39> pip install sqlalchemy

We have two approach 

1.Code first approach:

 Though using Code ,you need create the database design

2.Database first approach:

First need create/Design the database, after  u can write python code 

app.py

from sqlalchemy import create_engine,Column, Integer, String
from sqlalchemy.orm import declarative_base
from urllib.parse import quote_plus

DB_ENGINE = "mysql+pymysql"
DB_HOST = "localhost"
DB_PORT = 3306
DB_NAME = "ccitdb"
DB_USER = "root"
DB_PASSWORD = "root"
DATABASE_URL = f"{DB_ENGINE}://{DB_USER}:{quote_plus(DB_PASSWORD)}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
print(DATABASE_URL)

engine = create_engine(DATABASE_URL, echo=True)
Base = declarative_base()
# model creation start here
class Students(Base):
    __tablename__ = "students"

    id = Column(Integer, primary_key=True , autoincrement=True)
    name = Column(String(100) , nullable=False)
    email = Column(String(100), unique=True , nullable=False)
    mobile = Column(String(15), unique=True , nullable=False)

Base.metadata.create_all(engine)

    

Output: Table created success 

(ccitenv) PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day39> py app.py

mysql+pymysql://root:root@localhost:3306/ccitdb

2026-01-26 03:23:26,923 INFO sqlalchemy.engine.Engine SELECT DATABASE()

2026-01-26 03:23:26,923 INFO sqlalchemy.engine.Engine [raw sql] {}

2026-01-26 03:23:26,925 INFO sqlalchemy.engine.Engine SELECT @@sql_mode

2026-01-26 03:23:26,925 INFO sqlalchemy.engine.Engine [raw sql] {}

2026-01-26 03:23:26,928 INFO sqlalchemy.engine.Engine SELECT @@lower_case_table_names

2026-01-26 03:23:26,928 INFO sqlalchemy.engine.Engine [raw sql] {}

2026-01-26 03:23:26,931 INFO sqlalchemy.engine.Engine BEGIN (implicit)

2026-01-26 03:23:26,932 INFO sqlalchemy.engine.Engine DESCRIBE `ccitdb`.`students`

2026-01-26 03:23:26,932 INFO sqlalchemy.engine.Engine [raw sql] {}

2026-01-26 03:23:26,941 INFO sqlalchemy.engine.Engine 

CREATE TABLE students (

        id INTEGER NOT NULL AUTO_INCREMENT,

        name VARCHAR(100) NOT NULL,

        email VARCHAR(100) NOT NULL,

        mobile VARCHAR(15) NOT NULL,

        PRIMARY KEY (id),

        UNIQUE (email),

        UNIQUE (mobile)

)

2026-01-26 03:23:26,943 INFO sqlalchemy.engine.Engine [no key 0.00188s] {}

2026-01-26 03:23:27,017 INFO sqlalchemy.engine.Engine COMMIT


(here is drawback your unable alert the exist table, for this overcome the issue ,

need to follow memory management it exist in Django ,it has state of the table is called memory management )

 

Task 4: Insert the record using ORM

app.py

from sqlalchemy import create_engine,Column, Integer, String
from sqlalchemy.orm import declarative_base,sessionmaker
from urllib.parse import quote_plus

DB_ENGINE = "mysql+pymysql"
DB_HOST = "localhost"
DB_PORT = 3306
DB_NAME = "ccitdb"
DB_USER = "root"
DB_PASSWORD = "root"
DATABASE_URL = f"{DB_ENGINE}://{DB_USER}:{quote_plus(DB_PASSWORD)}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
print(DATABASE_URL)

engine = create_engine(DATABASE_URL, echo=True)
Base = declarative_base()
# model creation start here
class Students(Base):
    __tablename__ = "students"

    id = Column(Integer, primary_key=True , autoincrement=True)
    name = Column(String(100) , nullable=False)
    email = Column(String(100), unique=True , nullable=False)
    mobile = Column(String(15), unique=True , nullable=False)

Base.metadata.create_all(engine)

SessionLocal = sessionmaker(bind=engine)
session = SessionLocal()
new_student = Students(name="John Doe", email="john.doe@example.com", mobile="1234567890")
session.add(new_student)
session.commit()
print("Student added successfully")


Output:

(ccitenv) PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day39> py app.py

2026-01-26 03:30:38,420 INFO sqlalchemy.engine.Engine [generated in 0.00052s] {'name': 'John Doe', 'email': 'john.doe@example.com', 'mobile': '1234567890'}

2026-01-26 03:30:38,446 INFO sqlalchemy.engine.Engine COMMIT

Student added successfully


Task5:Select ORM

from sqlalchemy import create_engine,Column, Integer, String
from sqlalchemy.orm import declarative_base,sessionmaker
from urllib.parse import quote_plus

DB_ENGINE = "mysql+pymysql"
DB_HOST = "localhost"
DB_PORT = 3306
DB_NAME = "ccitdb"
DB_USER = "root"
DB_PASSWORD = "root"
DATABASE_URL = f"{DB_ENGINE}://{DB_USER}:{quote_plus(DB_PASSWORD)}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
print(DATABASE_URL)

engine = create_engine(DATABASE_URL, echo=True)
Base = declarative_base()
# model creation start here
class Students(Base):
    __tablename__ = "students"

    id = Column(Integer, primary_key=True , autoincrement=True)
    name = Column(String(100) , nullable=False)
    email = Column(String(100), unique=True , nullable=False)
    mobile = Column(String(15), unique=True , nullable=False)

Base.metadata.create_all(engine)

SessionLocal = sessionmaker(bind=engine)
session = SessionLocal()
new_student = Students(name="Subbu", email="vakati.subbu@gmail", mobile="9700217845")
new_student1 = Students(name="Karthik", email="karthik@gmail.com", mobile="9876543210")
session.add(new_student)
session.add(new_student1)
session.commit()
print("Student added successfully")

# read all students
students = session.query(Students).all()
print("All Students:")
for student in students:
    print(f"ID: {student.id}, Name: {student.name}, Email: {student.email}, Mobile: {student.mobile}")
session.close()


Output:

2026-01-26 03:36:30,566 INFO sqlalchemy.engine.Engine BEGIN (implicit)

2026-01-26 03:36:30,568 INFO sqlalchemy.engine.Engine SELECT students.id AS students_id, students.name AS students_name, students.email AS students_email, students.mobile AS students_mobile

FROM students

2026-01-26 03:36:30,568 INFO sqlalchemy.engine.Engine [generated in 0.00036s] {}

All Students:

ID: 1, Name: Subbu, Email: vakati.subbu@gmail, Mobile: 9700217845

ID: 2, Name: Karthik, Email: karthik@gmail.com, Mobile: 9876543210

2026-01-26 03:36:30,570 INFO sqlalchemy.engine.Engine ROLLBACK

 

Task6: For specific record, above code is same

app.py

# specific student by id
students = session.query(Students).filter_by(name="Subbu").all()
print("Specific Students:")
for student in students:
    print(f"ID: {student.id}, Name: {student.name}, Email: {student.email}, Mobile: {student.mobile}")
session.close()

Output:

2026-01-26 14:59:06,991 INFO sqlalchemy.engine.Engine SELECT students.id AS students_id, students.name AS students_name, students.email AS students_email, students.mobile AS students_mobile

FROM students

WHERE students.name = %(name_1)s

2026-01-26 14:59:06,992 INFO sqlalchemy.engine.Engine [generated in 0.00111s] {'name_1': 'Subbu'}

Specific Students:

ID: 1, Name: Subbu, Email: vakati.subbu@gmail, Mobile: 9700217845

2026-01-26 14:59:06,995 INFO sqlalchemy.engine.Engine ROLLBACK


Task7: Update and delete 

app.py

# update student
student = session.query(Students).filter_by(name="Subbu").first()
if student:
    student.email = "subbu.updated@gmail.com"
    session.commit()
    print("Student updated successfully")
else:
    print("Student not found")
# delete student
student = session.query(Students).filter_by(name="Karthik").first()
if student:
    session.delete(student)
    session.commit()
    print("Student deleted successfully")
else:
    print("Student not found")    
session.close()  

Specific Students:

ID: 1, Name: Subbu, Email: vakati.subbu@gmail, Mobile: 9700217845

2026-01-26 15:05:21,171 INFO sqlalchemy.engine.Engine SELECT students.id AS students_id, students.name AS students_name, students.email AS students_email, students.mobile AS students_mobile

FROM students

WHERE students.name = %(name_1)s

 LIMIT %(param_1)s

2026-01-26 15:05:21,172 INFO sqlalchemy.engine.Engine [generated in 0.00142s] {'name_1': 'Subbu', 'param_1': 1}

2026-01-26 15:05:21,177 INFO sqlalchemy.engine.Engine UPDATE students SET email=%(email)s WHERE students.id = %(students_id)s

2026-01-26 15:05:21,180 INFO sqlalchemy.engine.Engine [generated in 0.00293s] {'email': 'subbu.updated@gmail.com', 'students_id': 1}

2026-01-26 15:05:21,187 INFO sqlalchemy.engine.Engine COMMIT

Student updated successfully

2026-01-26 15:05:21,200 INFO sqlalchemy.engine.Engine BEGIN (implicit)

2026-01-26 15:05:21,201 INFO sqlalchemy.engine.Engine SELECT students.id AS students_id, students.name AS students_name, students.email AS students_email, students.mobile AS students_mobile

FROM students

WHERE students.name = %(name_1)s

 LIMIT %(param_1)s

2026-01-26 15:05:21,201 INFO sqlalchemy.engine.Engine [cached since 0.03067s ago] {'name_1': 'Karthik', 'param_1': 1}

2026-01-26 15:05:21,204 INFO sqlalchemy.engine.Engine DELETE FROM students WHERE students.id = %(id)s

2026-01-26 15:05:21,205 INFO sqlalchemy.engine.Engine [generated in 0.00106s] {'id': 2}

2026-01-26 15:05:21,209 INFO sqlalchemy.engine.Engine COMMIT

Student deleted successfully

So far we completed Code first approach, Database approach 

Database Approach:

You create the database first, then generate models from existing schema.


  • Migration using Flask and Django

What is a migration ?

A migration is a version-controlled change to your database schema.

It records what changed, when it changed ,and how to apply or undo it.

In One line: A migration is a step-by-step history of changes made to a database structure

Why Do we need migrations?
Databases are not static 
Your app grows ,so your tables change
Examples:
Add a new column
Remove a column
Rename a table 
Add a foreign key

Without migrations ?
(you manually alter dB, changes are undocumented, production & local db )


--Thanks 

 


 



Sunday, January 25, 2026

Python 32

 Web development Basics 

JavaScript Interactions and HTML

JavaScript can read, change, and control HTML elements after the page loaded

(HTML creates the page, JavaScript modifies the page dynamically).

How does JavaScript interact with HTML?

JavaScript uses something called the DOM

(The Dom represents the HTML page as objects that JavaScript can access and modify)

Common things JavaScript Does with HTML

Read input values, change text, change styles, Show/hide elements. respond to user actions, update page without reload

Task1: Display the ID value

index.html

<!DOCTYPE html>
<html lang="en">
        <title>Document</title>
        <script>
         function getvalue() {
          let val = document.getElementById("btn").innerText
          alert(val)
        }
        </script>
</head>
<body>
    <label id="lblName">Employee Name</label>
   <button id="btn" onclick="getvalue()">Click Me!</button>
</body>
</html>


Output: As you see here  document.getElementById("btn").innerText

it will show the value of the ID

PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day32> start index.html

document.getElementById("lblName").innerText

it will show the value of the ID, for This change, it will show the Employee Name


3.

 let val = document.getElementById("lblname").innerText="Welcome to CCIT"

If you change above , you can override the label value to Welcome to ccit


Task2: For this task, what every the text you have enter the value when click display alert for that value

Above code is same just change below line 

          let val = document.getElementById("txtName").value;
<body>
    <label id="lblName">Employee Name</label>
    <input type="text" id="txtName" />
   <button id="btn" onclick="getvalue()">Click Me!</button>
</body>

Output:


Task3:Style,Show hide text box

index.html

<!DOCTYPE html>
<html lang="en">
        <title>Document</title>
        <script>
         function HideText() {
            document.getElementById("secname").style.display = "none";

        }
         function ShowText() {
            document.getElementById("secname").style.display = "block";

        }
        </script>
</head>
<body>
    <section id="secname">
    <label id="lblName" style="color: blue;">Employee Name</label>
    <input type="text" id="txtName" />
    </section>
   <button id="btnhide" onclick="HideText()">Hide</button>
   <button id="btnshow" onclick="ShowText()">Show</button>

</body>
</html>

Output:

PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day32> start index.html


When Click Hide Button


 When click Show button


Task3: showpop

index.html

<!DOCTYPE html>
<html lang="en">
        <title>Document</title>

  <script>
         function myfunction() {
            var txt;
             if(confirm("Press a button!")) {
                txt = "You pressed OK!";
             } else {
                txt = "You pressed Cancel!";
             }
             document.getElementById("Demo").innerHTML = txt;
        }
        </script>      
</head>
<body>
    <h2>JavaScript Confirm Box</h2>
   <button id="btnshow" onclick="myfunction()">Try it</button>
   <p id="Demo"></p>

</body>
</html>

Output:

When click TryIt, shows popbox click Ok, text will display , when cancel , cancel text will display.



Introduction to AJAX

Asynchronous JavaScript and XML

AJAX Sending and Receiving data 


--Thanks 


Saturday, January 24, 2026

Python 34

Ajax part2

Store the data to csv or txt file 

Task1:

app.py

from flask import Flask, render_template, request,jsonify
import csv
import os

app = Flask(__name__)

@app.route("/")
def home():
    return render_template("index.html")    

@app.route("/RegisterData", methods=["POST"])

def register_data():
    data = request.get_json()
    file_name = "students.txt"
    file_exists = os.path.isfile(file_name)
    with open(file_name, mode="a", newline='') as file:
        writer = csv.writer(file)
        if not file_exists:
            writer.writerow(['name', 'age','gender'])
        writer.writerow([data['name'], data['age'], data['gender']])

    return jsonify({
        "status": "Success",
        "message": "Data received successfully"
    })
if __name__ == "__main__":
    app.run(debug=True)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
    <script>
        function clearData() {
            document.getElementById("name").value = "";
            document.getElementById("age").value = "";
            document.getElementById("gender").value = "";
        }
       
        function InsertData() {
         let Student = {
            name: document.getElementById("name").value,
            age: document.getElementById("age").value,
            gender: document.getElementById("gender").value
        };
          // document.getElementById("pdata").innerHTML = "Hello World!";
             fetch("/RegisterData", {
                 method: "POST",
                 headers: {'Content-Type': 'application/json'},
                 body:JSON.stringify(Student)
                })
               .then(response => response.json())
               .then(data => {
                   console.log('Success:', data);
                   alert("Data Registered Successfully!");
                   clearData();
               })
               .then(clearData())


        }

</script>
</head>
<body>
    <P id="pdata"></P>
    <table>
       <tr><td>name:</td><td><input type="text" id="name" /></td></tr>
      <tr><td>age:</td><td><input type="text" id="age" /></td></tr>
      <tr><td>gender:</td><td><input type="text" id="gender" /></td></tr>
      <tr><td>Course:</td>
      <td><select id="course">
          <option value="AWS">AWS</option>
          <option value="Devops2">Devops</option>
      </select></td></tr>
    </table>
    <button onclick="InsertData()">REGISTER DATA</button>
</body>
</html>

Output:

File created in the project level below text saved.
Student.txt

name,age,gender

subrahmanyam,34,Male

Karthik,28,Male



--Thanks




Python 33

Ajax:

JavaScripts sending a request to a python server(Flask/DJango) and receiving data(mostly JSON, not XML in modern applications)without reloading the page 

 

(Communicating with database, dynamically publish the data)

Introduction to Ajax:(Asynchronous JavaScript and XML)

"AJAX allows apart of a webpage to update without refreshing the whole page."

Build APIs using Flask/Django

Send  data using AJAX 

Update UI Dynamically

A JAX Works in 2 directions:

1.Send data to server 

2. Receive data from server

(Ajax usually use HTTP methods:GET,POST,PUT,DELETE)

Flask light weight tools

Practical

Task Step1: index.html

<!DOCTYPE html>
<html>
<head>
    <title>Document Title</title>
</head>
<body>
    <h1>Hello, World!</h1>
</body>
<button onclick="GetData()"> Get data</button>
<p id ="result"></p>


<script>
   function GetData(){
    fetch("/get_message").then(response => response.text()).then(data => {
       document.getElementById("result").innerText = data;
    });
   }
</script>
</html>

Step2:app.py

from flask import Flask, render_template
app = Flask(__name__) #Objet creation  
@app.route('/') #route definition
def home(): #function definition
    return render_template('index.html') #rendering template

@app.route('/get_message') #route definition
def get_message():
    return "Database Call" #simple function to return a message
if __name__ == '__main__': #main check
    app.run(debug=True) #app run in debug mode

Output:When click Getdata button ,without complete page load just publish the message that is called ajax call

Task2: Get data from .csv file 

app.py

from flask import Flask, render_template,jsonify
import csv
app = Flask(__name__) #Object creation  
@app.route('/') #route definition
def home(): #function definition
    return render_template('index.html') #rendering template

@app.route('/students') #route definition
def students123():
    students=[] #empty list to hold student data
    with open('student.csv',newline='') as csvfile: #opening csv file
        csvreader=csv.DictReader(csvfile) #reading csv file as dictionary
        for row in csvreader: #iterating through each row
            students.append(row) #appending row to students list
    return jsonify(students) #returning students list as JSON response

@app.route('/set_message') #route definition
def set_message():
    return "Set message Call" #simple function to return a message

if __name__ == '__main__': #main check
    app.run(debug=True) #app run in debug mode

inde.html

<!DOCTYPE html>
<html>
<head>
    <title>Document Title</title>
</head>
<body>
    <h1>Hello, World!</h1>
</body>
<button onclick="GetData()"> Get data</button>
<!--<p id ="result"></p>-->
<br> </br>
<table style="border: 2px solid black;" id="stdtable">
   <thead>
       <tr>
           <th>studentID</th>
           <th>studentName</th>
           <th>Course</th>
       </tr>
   </thead>

<tbody id="result">
 
</tbody>
</table>
<script>
   function GetData(){
    fetch("/students")
    .then(response => response.json())
    .then(data =>
    { let tablebody=document.getElementById("result");
      tablebody.innerHTML="";
      data.forEach(student=>{
        let row=`<tr>
                    <td>${student.student_id}</td>
                    <td>${student.name}</td>
                    <td>${student.course}</td>
                 </tr>`;
        tablebody.innerHTML+=row;
      });
      });
   }
</script>
</html>

student.csv 

student_id,name,course
10,Subrah,AWS
11,Ravi1,Tester
12,Karthik,Developer


Output 









Thanks 


Tuesday, January 20, 2026

python 38

Introduction to Django Framework:

Django is a high-level python web framework used to build secure, scalable, database-driven websites quickly.

Think of Django as: a complete toolbox to build websites using python

Why Django?

Fast development

Built-in security(SQL,injection,CSRF,XSS Protection)

Built-in ORM(no need to write sql manually)

Read-made admin panel 

Django feature:(user Authentication, admin dashboard, database ORM,URL routing,

forms & validation, security(CSRF,SQL injection).

MVT (Module view template)

Layer      Meaning  Role 

Model     database   database & data logic 

view        Logic      Business logic 

Template  UI          User Interface(HTML)

Step1: Create the Environment and activate

PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day38> python -m venv ccitenv

PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day38> Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned

PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day38> ccitenv/Scripts/activate 

Step2: Install Django

(ccitenv) PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day38> pip install django

Check environment using pip freeze command 

(ccitenv) PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day38> pip freeze

asgiref==3.11.0

Django==6.0.1

sqlparse==0.5.5

tzdata==2025.3

Step3: Start the project 

(ccitenv) PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day38> django-admin startproject ccitproject1

(ccitenv) PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day38>

Below screen automatically created these files, you have create view,templates ..etc 


You have to go inside the directory

(ccitenv) PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day38> cd .\ccitproject1

(ccitenv) PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day38\ccitproject1>

 Flask File structure 

  Projectname

    app.py

    templates /.html

    static  /css /.css

    static/image/.img/.png

    static/js/.js


Step4: in Django run the project use manage.py , just like we use in flask app.py   

(ccitenv) PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day38\ccitproject1> python manage.py runserver

This default page home for django



Step5: need to create view.py page here you need write business logic 

view.py 

def home():

 return "Welcome to Homepage!"

Step6:

You have register the page in urls.py file  , we have import views and route to home page give name to that 'home'

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

Output getting error: response issue 

C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day38\ccitenv\Lib\site-packages\django\core\handlers\exception.py, line 55, in inner

  1.                 response = get_response(request

Step7: We have inform which of response, you have to send the home page,

we have  different type of response 

html  "<h1>Welcome to ccit</h1>"

json  - {"course":"AWS"}

http 

Step8: see below first line is the http response

from django.http import HttpResponse

def home(request):
    return HttpResponse("<h1>Welcome to the Home page!</h1>")


Output :

(ccitenv) PS C:\Users\Administrator\Desktop\CCIT\PythonCourse\Day38\ccitproject1> python manage.py runserver


Step9: here urls.py page you have registered every page where you writing business logic (view.py)


Task2: json response planning to send response to home page 

Step1:

view.py

from django.http import HttpResponse
from django.http import JsonResponse

def home(request):
    return HttpResponse("<h1>Welcome to the Home page!</h1>")

def course(request):
    data = {
        'course_name': 'Django Web Development',
        'duration': '6 weeks',
        'level': 'Beginner'
    }
    return JsonResponse(data)

urls.py

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

Output:

Task3: 
Step1:

home.html

<h1>Welcome to the Home page CCIT!</h1>

view.py

from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render

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

def course(request):
    data = {
        'course_name': 'Django Web Development',
        'duration': '6 weeks',
        'level': 'Beginner'
    }
    return JsonResponse(data)

Step2: We have define our project 'ccitproject1', and give templates DIRS 'DIRS': ['templates'],

We have to register the hom.html in settings.py file 

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'ccitproject1',
]
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },

urls.py 

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

Output: We have return html page 




Task4:

We have copy the index.html which was worked earlier copy the text to home.html

home.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cloud Computing In Telugu</title>
    <link rel="stylesheet" href="static/css/style.css">
</head>
<body>
<nav >
    <ul class="menu">
        <li><a href = "/">Home</a></li>
        <li><a href="/aboutus">About Us</a></li>
        <li><a href="/contactus">Contact Us</a></li>
       
    </ul>
</nav>
    <!-- Header Section -->
    <header>
    <h1>AWS Cloud Computing</h1>
    <section>
              <p>Learn how websites are built from scratch</p>
    </header>
    <main>
 
        <section id="sec4">
            <form method="post" >
            <button type="submit">Enroll Now</button>
            {% if msg %}
                {{ msg|safe }}
            {% endif %}
        </form>

            <h2>Join Our Cloud Computing Course Today!</h2>
         </section>
    </main>
    <!-- Footer -->
    <footer>
        <p>Regards,</p>
        <p>
            <a href="https://www.Google.com" target="_blank">
                Google Page
            </a>
        </p>
    </footer>
</body>
</html>

contactus.html same aboutus.html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cloud Computing In Telugu</title>
    <link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
<nav >
    <ul class="menu">
        <li><a href = "/">Home</a></li>
        <li><a href="/aboutus">About Us</a></li>
        <li><a href="/contactus">Contact Us</a></li>
       
    </ul>
</nav>
    <!-- Header Section -->
    <header>
    <h1>AWS Cloud Computing</h1>
    <section>
              <p>Learn how websites are built from scratch</p>
    </header>
    <main>
        <h2>Join Our Cloud Computing Course Today! Contact us</h2>
    </main>
    <!-- Footer -->
    <footer>
        <p>Regards,</p>
        <p>
            <a href="https://www.Google.com" target="_blank">
                Google Page
            </a>
        </p>
    </footer>
</body>
</html>

view.html

from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render

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

def course(request):
    data = {
        'course_name': 'Django Web Development',
        'duration': '6 weeks',
        'level': 'Beginner'
    }
    return JsonResponse(data)

def aboutus(request):
        return render(request, 'aboutus.html')
# register the contactus view
def contactus(request):
    return render(request, 'contactus.html')

setting.py no change same as above 


Output: 

Aboutus Page , it will automatically route to aboutus.page

Contactus page:http://127.0.0.1:8000/contactus/

Home page: http://127.0.0.1:8000/

Task5: 

Multiple html page repeated code, to over come need to write base.html extended the base.html to

 all html page for main script 

base.html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cloud Computing In Telugu</title>
    <link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
<nav >
    <ul class="menu">
        <li><a href = "/">Home</a></li>
        <li><a href="/aboutus">About Us</a></li>
        <li><a href="/contactus">Contact Us</a></li>
       
    </ul>
</nav>
    <!-- Header Section -->
    <header>
    <h1>AWS Cloud Computing</h1>
    <section>
              <p>Learn how websites are built from scratch</p>
    </header>
    <main>
     {% block content %}
     {% endblock %}
    </main>
    <!-- Footer -->
    <footer>
        <p>Regards,</p>
        <p>
            <a href="https://www.Google.com" target="_blank">
                Google Page
            </a>
        </p>
    </footer>
</body>
</html>

home.html

{% extends 'base.html' %}

{% block content %}
<h2>Join Our Cloud Computing Course Today! Home</h2>
{% endblock %}

contactus.hmtl

{% extends 'base.html' %}

{% block content %}
<h2>Join Our Cloud Computing Course Today! Contactus</h2>
{% endblock %}

aboutus.html

{% extends 'base.html' %}

{% block content %}
<h2>Join Our Cloud Computing Course Today! aboutus</h2>
{% endblock %}


Advantage if anything adding page just add the line in base.html  it will effect home page 

       <li><a href="/course">Course</a></li>


course.html

{% extends 'base.html' %}

{% block content %}
<h2>Join Our Cloud Computing Course Today! Course </h2>
<p>Course Name: {{ course_name }}</p>
<p>Duration: {{ duration }}</p>
<p>Level: {{ level }}</p>
{% endblock %}

Output:












--Thanks  Tomorrow  session

Model (M) --Data Layer 

  • A Model is a python class that represents a database  table
  • Attributes inside the class define the table columns and their data types.
  • Models store and manage application data.
  • UI pages are generated using model data via view and templates.

Example: view.py

 from django.db import models

class student(models.Model):

 name= models.CharField(Max_length=100)

age= models.IntegerField()

email= models.EmailField()

Each class -->table

Each field -->column

Django ORM handles SQL for you

You can able Write url way also just for refernce

 <li><a href="{/aboutus">About Us</a></li>
        <li><a href="/contactus">Contact Us</a></li>
        <li><a href="/course">Course</a></li>

OR 
       <li><a href="{% url 'aboutus' %}">About Us</a></li>
        <li><a href="{% url 'contactus' %}">Contact Us</a></li>
        <li><a href="{% url 'course' %}">Course</a></li>

--Thanks