0% found this document useful (0 votes)
23 views126 pages

FulStack-module1,2 (1)

full stack development vtu model and 2 notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views126 pages

FulStack-module1,2 (1)

full stack development vtu model and 2 notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 126

Full Stack Development

What is Full Stack?


Front End Back End Ful Stack
The part of a website The behind-the-scenes •Refers to developers who
you can see and part that stores and work on both frontend and
interact with. processes data. backend aspects of web
Includes buttons, Handles tasks like saving development.
forms, and all the user information, •Full-stack developers can
content you can view managing databases, and build entire web
on a webpage. making websites work applications from scratch,
Built with HTML for smoothly. handling everything from
structure, CSS for Uses server-side user interfaces to database
styling, and JavaScript languages like Python or interactions.
for interactivity Node.js, along with
databases.
What are Full-Stack Frameworks?
Frontend and Backend Together:
• A full-stack framework is like a toolkit that includes everything you need to build both the
frontend (what users see) and backend (what happens behind the scenes) of a website or web
application.
• It's like having a complete set of tools in one box to create an entire project.
Benefits of Using Full-Stack Frameworks:
• Saves Time: Since everything you need is already included, you don't have to start from scratch
and can build faster.
• Consistency: Full-stack frameworks provide consistent ways to handle frontend and backend
tasks, making your code more organized.
• Easier Learning Curve: They often have clear documentation and tutorials, making it easier for
beginners to learn and use.
Examples of Full-Stack Frameworks
MEAN Stack MERN Stack Django Python

• MongoDB (database) • MongoDB(database) • Python (backend)


• Express.js (backend) • Express.js (backend) • Django framework
• Angular (frontend) • React (frontend) (frontend and
• Node.js (runtime backend tools)
• Node.js (runtime
environment) environment) • Django REST
Framework (API
development)
Intro. to Django
Django is a web application framework written in Python programming language.
Enables rapid development of secure and maintainable websites
It follows the MVC (Model-View-Controller) architectural pattern, although in Django it's often
referred to as MTV (Model-Template-View) due to its slightly different implementation.
Django allows you to focus on the core of Web application. It streamlines web development
by offering
• Ready-to-use solutions,
• Simplifying complex tasks,
• Enforcing clear coding conventions
• Allowing flexibility for customization and extension as per the project requirements.
What Is a Web Framework?

Early Days of
Web
Development
Framework
•A framework is a prebuilt collection of libraries, modules and tools that
provides a structured approach to developing software applications.

Django is a web development framework.


AngularJS is a web front end development framework
React is a web front end development library
Problems Addressed by Web
Framework
• Copying database connections and other tasks for
1.Code Duplication each page leads to mistakes and wastes time.

Boilerplate Code and • Routine tasks like setting up pages become tedious
Productivity and can slow down developers.

1.Environment-
• Managing different databases and settings for
Specific different servers becomes challenging.
Configurations

Separation of Logic • Mixing code and design makes it hard for designers
and Presentation to change the look without affecting functionality
Django Evolution
1. Write a web application from scratch.
2. Write another web application from scratch.
3. Realize application from step1 shares much in common with application in
step2
4. Refactor the code so that application-1 shares code with application-2.
5. Repeat steps 2-4 several times.
6. Realize you’ve invented a framework.
MVC (Model-View-Controller) Pattern

• Software design pattern used in web development to separate the different components of an
application, making it easier to manage, maintain, and scale.
• The MVC pattern separates the concerns of data, presentation, and application logic, allowing
developers to work on each component independently.
MVC Pattern
Model •Represents the data and business logic of the application.
• Manages the data structure, storage, and manipulation (e.g., database interactions).
• Examples: Python classes in Django's models.py file that define database tables and relationships.

View •Handles the presentation and user interface of the application.


• Displays data from the model to users and collects user inputs.
Examples: HTML templates in Django's templates folder that define the structure and design of web
pages.

Controller •Manages the flow of the application and handles user inputs and requests.
• Interacts with both the model and view to process requests, retrieve data, and render responses.
Examples: Python functions or classes in Django's views.py file that define the logic for handling HTTP
requests and generating responses.
Advantages of MVC
MVC separates concerns, allowing for easier maintenance and changes:
• Components are loosely coupled, meaning they can be modified independently
without affecting others.
• Changes in URLs, HTML design, or database structure can be made without
extensive code modifications.
• Developers, designers, and database administrators can work on their respective
areas without interfering with each other's tasks.
• Consistent Design: Django maintains a clean design & makes it easy to follow web
development practices.
• Less code & not repeated
Django MVT (Model -View-Template)
The MVT is a software design pattern which includes three important
components Model, View and Template.
• The Model helps to handle database. It is a data access layer which handles
the data.
• The Template is a presentation layer which handles User Interface part
completely.
• The View is used to execute the business logic and interact with a model to
carry data and renders a template.
Full Stack Development with Django
Python Virtual Environment
A Python Virtual Environment is an isolated space where you can work on your Python
projects, separately from your system-installed Python.
You can set up your own libraries and dependencies without affecting the system
Python.
There are no limits to the number of virtual environments
It allows you to have multiple Python environments with different versions of Python
and different sets of installed packages on the same system.
It is generally good to have one new virtual environment for every Python-based
project you work on
You can change the system python version, django version and other dependencies
without affecting the project python version, django versions and dependencies
Django Project & App
Structure
DJANGO USES A DIRECTORY STRUCTURE TO ARRANGE THE
DIFFERENT PARTS OF THE WEB APPLICATION . NOW, WE WILL LEARN
ABOUT THESE IN MORE DETAIL FOR BOTH PROJECT AND THE APP.
Creating a new Django Project
A project is the fundamental unit of your Django web application.
Django project – a collection of settings for an instance of Django,
including database configuration, Django-specific options and
application-specific settings.
django-admin startproject my_project .
Project File Structure
This is what the default Django project structure looks like.
Root Directory of the Project

Project Package
Functions of Different Files
manage.py –
file provides a command-line utility for a Django project.
Use this command-line utility to perform various operations related to debugging, running, and
deploying a Django web application.
 For example, to run a Django application in the development server you will use the following
command:
python manage.py runserver

_init_.py
 Empty Python file. The _init_.py file tells the Python interpreter that the directory is a Python package
Functions of Different Files
settings.py
The main configuration file for a Django project.
This file contains all the settings for your Django project, such as database configuration, static files,
middleware, etc.

urls.py
 The urls.py file defines URL patterns that Django will use to match incoming HTTP requests with
corresponding view functions or classes.
It acts as a central hub for defining how incoming URL’s should be handled within the Django project.
Django App
Inside a project, an app is used for handling a
particular section of the website.
In a typical web application, one app is used entirely
for User Authentication, one entirely for Payments,
etc.
Run the following command to create the apps from
within the project root folder.
python manage.py startapp hello_world_app
Django App file structure
_init_.py
 It remains empty and is present just to indicate that the specific app directory is a package.

admin.py
The admin.py file in each Django app is where you can register your models to make them
accessible and manageable through the admin interface.

apps.py
 The file contains the application specific configuration.
 allows you to configure various aspects of your app, such as its name, verbose name, and
any application-specific settings you might want to define.
Django App file structure
models.py
The models.py file is where you define the database models for your
application.
A model is a Python class that represents a database table, and each
attribute of the class corresponds to a database field.
tests.py
This file contains unit tests for the app.
views.py
Define the view functions or classes that handle HTTP requests and
return HTTP responses.
By defining views in the views.py file, you create the logic that drives
your web application's behavior.
Creating View
To create a view, write a view function or simply a view for short
Create view by creating a Python function in your ‘views.py’ file.
A python function that takes an HTTP request as input and return an HTTP response.
The view itself contains whatever arbitrary logic is necessary to return that response.
This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an
XML document.
Sample views.py
Mapping URLs to Views(URLconf)
A mapping between URL patterns and the view functions that should be called
for those URL Patterns.
“For this URL, call this code, and for that URL, call that code”
Once you've defined your views, you need to map them to URLs in your Django
project's urls.py file.
urls.py(URLconf) file is created when a Django project is created
This code snippet is from a Django project's urls.py file. It defines a
URL pattern using the path() function imported from django.urls
module. Let's break down each part:
Import statements
imports the path() function, which is used to
define URL patterns.

imports the views module from the helloapp


Django app. This assumes that there's a
module named views.py inside the helloapp
directory, which contains view functions or
classes.
URL Pattern Definition
urlpatterns is a list that contains URL
patterns for the web application. Each
URL pattern is defined as a path()
function call.
Inside the path() function:
'time/' is the URL pattern string. It specifies the URL path that the view will respond to. In
this case, the view will be triggered when the user visits `/time/` URL.
‘views.current_datetime’ is the view function that will be called when the URL pattern is
matched.
Here, current_datetime is assumed to be a view function defined in the views.py module
of the helloapp app.
How Django
Processes a
Request
Dynamic URLS
URLs with variable parts that change based on parameters or user input.
Example:
◦ /blog/post/1,
◦ /products/category/electronics.

To capture a value from the URL, use angle brackets.


Captured values can optionally include a converter type. For example, use
<int:name> to capture an integer parameter.
Django supports dynamic URL routing using Path Converters
• Path converters are used within URL patterns to capture dynamic segments of a URL.
• Allow you to define URL patterns that can match varying parts of a URL and pass
them as arguments to your views
Common Path Converters
<int:value>
Matches zero or any positive integer. Returns an int.
<str:value>
Matches any non-empty string, excluding the path separator, '/’.
This is the default if a converter isn’t included in the expression.
<slug:value>
Matches any slug string consisting of ASCII letters or numbers, plus the hyphen
and underscore characters.
For example, building-your-1st-django-site.
Common Path Converters
<uuid:value>
Matches a formatted UUID.
To prevent multiple URLs from mapping to the same page, dashes must be
included and letters must be lowercase.
For example, 075194d3-6885-417e-a8a8-6c931e272f00. Returns a UUID
instance.
<path:value>
Matches any non-empty string, including the path separator, ‘/ ’.
This allows you to match against a complete URL path rather than a segment
of a URL path as with str.
Sample URLconf:
Example requests
A request to /articles/2005/03/ would match the third entry in the list. Django
would call the function views.month_archive(request, year=2005, month=3).
/articles/2003/ would match the first pattern in the list, not the second one,
because the patterns are tested in order, and the first one is the first test to
pass. Feel free to exploit the ordering to insert special cases like this. Here,
Django would call the function views.special_case_2003(request)
/articles/2003 would not match any of these patterns, because each pattern
requires that the URL end with a slash.
/articles/2003/03/building-a-django-site/ would match the final pattern.
Django would call the function views.article_detail(request, year=2003,
month=3, slug="building-a-django-site").
Full Stack Development with Django
Django Templates and
Models
Outline - Templates
Template System Basics
Using Django Template System
Basic Template Tags and Filters
Template Loading
Template Inheritance
What are Django Templates?
Django templates are files containing HTML along with template tags and
variables.
These template tags and variables are replaced with actual data when the
template is rendered.
The rendered HTML is then sent back to the user's browser as an HTTP
response.
They allow you to build web pages with dynamic data, logic, and structure.
Django's template system allows you to separate the presentation layer (HTML)
from the business logic (views), promoting code organization and maintainability
Why Django Template?
In Django, the approach to web design is straightforward: maintain a clear
separation between Django's logic and code from the design aspects.
We recognize that HTML serves as a static markup language, whereas Python
offers dynamic programming capabilities.
Django's template engine facilitates this segregation by enabling the creation
of dynamic web pages, effectively separating design concerns from the Python
codebase.
Templates promote code reuse by allowing you to define common layout
structures and components once and reuse them across multiple pages
or views. This reduces redundancy and makes code more efficient.
Variables

Filters

Tags
Basics of Template
Syntax: Django templates use a syntax that is similar to Python but designed to be
simple and easy to use. You can embed Python-like code inside HTML using template
tags and filters.
Template Tags: Template tags are enclosed within {% %}. They control the logic and flow
of the template. For example, you can use {% if %}, {% for %}, {% include %}, etc., for
conditional logic, loops, and including other templates respectively.
Template Variables: Template variables are enclosed within {{ }}. They represent
dynamic content that will be replaced with actual values when the template is rendered.
You can access variables passed from views or context processors.
Filters: Filters are used to modify the output of variables. They are appended to variables
with a pipe symbol ‘|’. Filters can perform operations like formatting dates, converting
text to uppercase, etc.
Creating a Template
Step 1: Create a Templates Directory
Inside your Django app directory, create a directory named templates. This is where your HTML
templates will reside.
myapp/
├── migrations/
├── templates/ <-- Create this directory
└── ...
Creating a Template
Step 2: Define Your Template
Create an HTML file within the templates directory. You can use any text editor or IDE to create
the file. For example, let's create a template named index.html:
Creating a Template
Step 3: Using Templates in Views
Inside your Django app's views (views.py), import the render function from
django.shortcuts. This function is used to render templates.
Rendering Templates
1. Rendering Process:
Rendering a template involves combining the template file with data from the context to generate
HTML output.
Django's rendering engine processes the template file and replaces template tags and variables with
actual data from the context.

2. View Function:
In a Django view function, the render() method is used to render a template.
The render() method takes the HTTP request, template file path, and context data as arguments.
Rendering Templates
3. Context Data:
Context data is a dictionary-like object containing variables and their associated values to be passed
to the template.
It is represented by the Context class in Django, located in the django.template module.
The Context class constructor takes an optional argument, a dictionary mapping variable names to
variable values.
These variables are accessed within the template using template
variables ({{ }}).
Example Code:
Example Code:
Context Variable Lookup
Understanding how to traverse/access complex data structures in Django
templates using the dot character (.).
Data can also be passed to templates in the form of lists, dictionaries, and
custom objects.
Dot Notation:
In Django templates, use the dot character (.) to access dictionary keys, object
attributes, indices, or methods of an object.
Dot notation allows for convenient traversal of complex data structures.
Context Variable Lookup
Accessing Dictionary Values:
To access values from a dictionary stored in the context, use dot notation
followed by the dictionary key.
template.html

views.py
Accessing Object Attributes:
Dot notation can also be used to access attributes of objects stored in the
context.
Method Calls: Dot notation can be used to call methods on objects stored in the
context.
<body>
<h1>User Info</h1>
<p><strong>Name (uppercase):</strong> {{ user.name.upper }}</p>
</body>
Note that parentheses are not included in the method calls.
Only methods that have no required arguments can be called in templates.
Accessing List Indices:
Dot notation is used to access list indices within the context.
Negative list indices are not allowed in Django templates.
Example:
<body>
<h1>Item Details</h1>
<p><strong>Second Item:</strong> {{ items.1 }}</p>
</body>
Handling Invalid Variables
Silent Failure:
If a variable is not found in the context, Django's template engine fails silently.
It does not raise an error or exception but rather renders an empty string for
the missing variable.
This ensures that the template continues to render without interruption,
even if some data is missing.
Built in Tags & Filters
Using {% if %} and {% else %} - Tags
The {% if %} tag evaluates a <html><head><title>{{title}}</title></head>
variable, <body> <h1>{{heading}}</h1>
if that variable is "true" {% if user.is_authenticated %}
(i.e., it exists, is not empty, and is <p>Welcome back,{{user.username }}!</p>
not a false Boolean value). {% else %}
The system will display <p>Welcome, guest!
everything between {% if %} and
Please <a href="/login/">log in</a>.</p>
{% endif %},
{% endif %}
</body>
</html>
Using Logical Operators
The {% if %} tag can test multiple variables using logical operators : and, or, not
Example with: and
{% if athlete_list and coach_list %}
<p>Both athletes and coaches are available.</p>
{% endif %}
Example with: or
{% if athlete_list or coach_list %}
<p>There are some athletes or some coaches.</p>
{% endif %}
Example with: not
{% if not athlete_list %}
<p>There are no athletes.</p>
{% endif %}
Combining Logical Operators
Combine and, or, not to handle more complex logic
The precedence of the operators, from lowest to highest, is as follows:
or least
and
the following complex if tag:
not
{% if a == b or c == d and e %}
in
will be interpreted as:
==, !=, <, >, <=, >=
(a == b) or (( c == d) and e)
Combining Logical Operators
Combine and, or, not to handle more complex logic
Examples: No Athletes or Some Coaches:
{% if not athlete_list or coach_list %}
<p>There are no athletes or there are some coaches.</p>
{% endif %}
Example: Product Availability
Scenario: Display messages based on product availability.
{% if products and in_stock %}
<p>Products are available and in stock!</p>
{% elif products %}
<p>Products are available but out of stock.</p>
{% else %}
<p>No products available.</p>
{% endif %}
Task
Create a template that displays user status based on multiple conditions.
Create a file user_status.html.
Conditions to Implement:
1. If the user is authenticated and an admin, display "Welcome, Admin!"
2. If the user is authenticated but not an admin, display "Welcome, User!"
3. If the user is not authenticated, display "Welcome, Guest! Please log in."

context = {
'user': {
Sample Context Data 'is_authenticated': True,
'is_admin': False,
'username': 'john_doe'
}
}
Using the {% for %} Tag
The {% for %} tag allows you to loop over a sequence (e.g., a list, dictionary,
queryset)
And render a block of content for each item in that sequence.
Basic Syntax
{% for item in sequence %}
<!-- Code to execute for each item -->
{% endfor %}
Example: Looping Over a List
<ul>
{% for product in products %}
<li>{{ product.name }}: ${{ product.price }}</li>
{% endfor %}
</ul>
Advanced Usage of {% for %} Tag
Using Loop Variables:
Django provides several built-in variables within a {% for %} loop
Variable Description
forloop.counter The current iteration of the loop (1-indexed)
forloop.counter0 The current iteration of the loop (0-indexed)
forloop.revcounter The number of iterations from the end of the loop (1-indexed)
forloop.revcounter0 The number of iterations from the end of the loop (0-indexed)
forloop.first True if this is the first time through the loop
forloop.last True if this is the last time through the loop
forloop.parentloop For nested loops, this is the loop surrounding the current one
<ul>
{% for product in products %}
<li>
{{ forloop.counter }}. {{ product.name }}: ${{ product.price }}
{% if forloop.first %}(First item!){% endif %}
{% if forloop.last %}(Last item!){% endif %}
</li>
{% endfor %}
</ul>
Looping Over a Dictionary
When looping over dictionaries, use .items to access the key-value pairs.

<ul>
{% for key, value in dictionary.items %}
<li>{{ key }}: {{ value }}</li>
{% endfor %}
</ul>
Nested Loops
You can nest {% for %} loops to handle nested data structures like lists within
lists or lists within dictionaries.
<ul>{% for category in categories %}
<li>{{ category.name }}
<ul>{% for product in category.products %}
<li>{{ product.name }}: ${{ product.price }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
Handling Empty Lists
Use the {% empty %} tag to provide fallback content if the list is empty.
<ul>
{% for product in products %}
<li>{{ product.name }}: ${{ product.price }}</li>
{% empty %}
<li>No products available.</li>
{% endfor %}
</ul>
Task
Create a template student.html that uses the {% for %} loop to iterate over the
students and display their details.

students = [
{'name': 'Alice', 'grade': 'A'},
{'name': 'Bob', 'grade': 'B'},
{'name': 'Charlie', 'grade': 'C'},
]
return render(request,"students.html",students)
Comments
Django template language allows for comments.

{# this is a comment #}  Single line comment

{% comment %}
Multiline comments
This is a multi line comment
{% endcomment %}
Filters
Allow for the alteration and formatting of variables before they are
rendered on the webpage.
By using filters, developers can ensure that the data is displayed in the desired
format and is safe for rendering.
Applying Filters
Filters are applied using a pipe ( | ) symbol.

{{ name|lower }}

Takes the variable name and applies the lower filter, which converts the text to
lowercase.
Chaining Filters
Multiple filters can be applied sequentially by chaining them together.

{{ my_text | escape | linebreaks }}

First applies the escape filter to convert special characters to their HTML-safe
equivalents and
Then applies the linebreaks filter to convert newline characters to <p> tags.
Filters with Arguments
Some filters require additional arguments.
These arguments are specified in double quotes and follow a colon.
For example, to truncate a text to a specific number of words:

{{ bio|truncatewords:"30" }}

This will display only the first 30 words of the bio variable.
Common Filters
addslashes: Adds slashes before quotes & backslashes
Useful for escaping strings in CSV/javascript
for example.

Input : text = "I'm using \ Django"

Filter :  {{ text|addslashes }}

Output:  I\'m using \\ Django


Common Filters
date: Formats date and datetime objects according to the given format string.

{{ pub_date | date:"F j, Y" }}  March 14, 2024

escape: Escapes special HTML characters to ensure the text is safe for HTML rendering. This
is crucial for preventing XSS (Cross-Site Scripting) attacks.

• Converts & to &amp;


user_input = "<script>alert('XSS');</script>"
• Converts < to &lt;
• Converts > to &gt; {{ user_input | escape }}
• Converts " (double quote) to
&quot; &lt;script&gt;alert(&#39;XSS&#39;);&lt;/script&gt;
• Converts ' (single quote) to &#39;
Common Filters
post.title = “a wonderFul tRip“

{{ post.title | upper }} A WONDERFUL TRIP


{{ post.title | lower }} a wonderful trip
{{ post.title | title }} A Wonderful Trip
{{ post.title| title |truncatewords:2}} A Wonderful...
{{post.title | title |truncatechars:8 }} A Wonder
Philosophies and Limitations of the
Django Template System
These principles help explain
why the Django template system works the way it does and
why it might differ from other template languages.
1. Business logic should be separated from presentation logic.
2. Syntax should be decoupled from HTML/XML.
3. Designers are assumed to be comfortable with HTML code.
4. Designers are assumed not to be Python programmers.
5. The goal is not to invent a programming language.
Separation of Business Logic and
Presentation Logic
Principle: Templates should handle presentation and presentation-related logic
only.
Implication: The template system should not support functionality beyond
controlling presentation. This ensures a clear separation between what the
template does (display logic) and what the backend does (business logic).
Example: You cannot call Python code directly in Django templates. All
programming is limited to the scope of template tags. Custom tags can be
created for specific needs, but out-of-the-box tags do not allow arbitrary Python
code execution.
Decoupled Syntax from HTML/XML
Principle: The template syntax should be usable for non-HTML formats, such as
plain text.
Implication: Unlike some other template languages that embed logic within XML
tags or attributes, Django avoids this to prevent the overhead and errors
associated with XML parsing.
Example: Templates can generate plain text, emails, or any other text-based
format, not just HTML.
Comfort with HTML Code
Principle: The template system assumes that designers are comfortable with
HTML.
Implication: Templates are not optimized for WYSIWYG editors but for direct
HTML editing, allowing for a cleaner and more powerful syntax.
Example: Template authors write HTML directly and embed template tags
where necessary.
Catering to Non-Python Programmers
Principle: Templates are often written by designers, not programmers.
Implication: The template language is simple and does not require knowledge of
Python. However, it still provides enough functionality for small teams where
Python programmers create templates.
Example: Simple tags and filters are used instead of raw Python code. Custom
tags can be created to extend functionality if needed.
Avoiding the Creation of a Full
Programming Language
Principle: The template language is not intended to be a full-fledged
programming language.
Implication: It offers just enough functionality (e.g., branching and looping) to
make presentation-related decisions without overcomplicating the template.
Example: Basic control structures like {% if %} and {% for %} are available, but
templates cannot perform complex computations or change variable values.
Limitations of the Django Template
System
1. No Variable Setting:
Limitation: A template cannot set or modify variables.
Reason: This maintains the separation of logic and presentation, ensuring that
templates only display data passed to them.
1. No Raw Python Code Execution:
Limitation: Templates cannot execute raw Python code.
Reason: This prevents mixing business logic with presentation logic and keeps
templates simple and secure.
Workaround: Custom template tags and filters can be created to overcome
these limitations.
{% include %} - Template Tag
The {% include %} template tag in Django is used to include the contents of
another template within the current template.
The argument to the tag should be the name of the template to include
{% include "header.html" %}
The template name can be either a variable or a hard-coded (quoted) string, in
either single or double quotes.
{% include template_name %}
This is useful for reusing common elements across multiple templates or for
breaking down large templates into smaller, more manageable parts.
{% include %} - Template Tag
Template File: The name specified in the {% include %} tag should be the path
to the template file relative to the directories specified in the DIRS setting of the
TEMPLATES configuration in your Django project's settings.
Context: By default, the included template inherits the context of the parent
template. However, you can pass additional context data to the included
template by providing a dictionary of key-value pairs after the template name.
{% include "header.html" with title="Page Title" %}
<!-- header.html -->
<!-- homepage.html --> <header>
{% include "header.html" %} <h1>My Website</h1>
<div class="content"> <nav>
<h2>Welcome to our website!</h2> <ul>
<!-- Main content goes here --> <li><a href="/">Home</a></li>
</div> <li><a href="/about/">About</a></li>
{% include "footer.html" %} <li><a href="/contact/">Contact</a></li>
</ul>
</nav>
</header>

<!-- aboutpage.html -->


{% include "header.html" %}
<div class="content">
<h2>About our website!</h2>
<!-- Main content goes here --> <!-- footer.html -->
</div> <footer>
{% include "footer.html" %} <p>&copy; 2024 My Website. All rights
reserved.</p>
</footer>
Template Inheritance
How do you reduce the duplication and redundancy of common page areas,
such as sitewide navigation?
Template inheritance is designed to manage the overall structure(“skeleton”)
of a website
By creating a base template that defines a common structure and layout.
Child templates can then extend this base template and override or add
specific blocks of content
<html lang="en"> base.html
<head>
<link rel="stylesheet" href="style.css">
<title>{% block title %}My amazing site{% endblock %}</title>
</head>

<body>
<div id=“navbar">
{% block navbar %}
<ul>
<li><a href="/">Home</a></li>
<li><a href="/blog/">Blog</a></li>
</ul>
{% endblock %}
</div>

<div id="content">
{% block content %}{% endblock %}
</div>
</body>
</html>
Child.html Must be the First Template tag

{% extends "base.html" %}

{% block title %}My amazing blog{% endblock %}

{% block content %}

{% for entry in blog_entries %}


<h2>{{ entry.title }}</h2>
<p>{{ entry.body }}</p>
{% endfor %}

{% endblock %}
Three level approach
One common way of using inheritance is the following three-level approach:
1. Create a base.html template that holds the main look-and-feel of your site.
2. Create a base_SECTIONNAME.html template for each “section” of your site.
For example, base_news.html, base_sports.html. These templates all extend
base.html and include section-specific styles/design.
3. Create individual templates for each type of page, such as a news article or
blog entry. These templates extend the appropriate section template.
Interacting With
Database: Models
Configuring Database
Configuring the database in Django involves setting up the DATABASES setting in
your project's settings.py file.
Configuring the database is a crucial step because it tells Django
how to connect to the database
 where this data will be stored
Key Components of Django's Database Configuration
1. Settings file
2. DATABASES Dictionary
Key Components of Django's Database
Configuration
1. Settings File: In Django, the database configuration is done in a file called
`settings.py`. This file contains various settings for your Django project,
including how to connect to the database.
2. DATABASES Dictionary: Within settings.py, there is a special dictionary called
DATABASES. This dictionary holds all the information Django needs to connect
to your database.
1. Steps to Configure: Install MySQL and the `mysqlclient` adapter.
2. Update the DATABASES dictionary in settings.py.

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # The backend for MySQL
'NAME': 'your_db_name', # The name of your database
'USER': 'your_db_user', # Your database username
'PASSWORD': 'your_db_password', # Your database password
'HOST': 'localhost', # The database server
'PORT': '3306', # The port MySQL runs on
}
}
ENGINE
This setting specifies the database backend to use. Django supports several
database backends:
'django.db.backends.sqlite3' for SQLite.
'django.db.backends.postgresql' for PostgreSQL.
'django.db.backends.mysql' for MySQL.
'django.db.backends.oracle' for Oracle.
Custom backends can also be specified if additional ones are installed (e.g., for
Microsoft SQL Server or other databases).
NAME
The name of your database. For SQLite, this should be the path to your database
file (e.g., BASE_DIR / "db.sqlite3"). For other databases, this is the
name of the database schema.
USER
The username to use when connecting to the database.
This is not used with SQLite since it doesn’t require authentication.
PASSWORD

The password to use when connecting to the database. This is also not used with
SQLite.

HOST

The hostname of the database server. Use 'localhost' for local


development, or the IP address/domain name of the database server for remote
connections. For SQLite, this can be left as an empty string or set to None.
PORT

The port number on which the database server is listening. Use the default port
of your database server (e.g., 5432 for PostgreSQL, 3306 for MySQL). For
SQLite, this can be left as an empty string or set to None.
OPTIONS

A dictionary of additional options to pass to the database backend. This can be


used to set various backend-specific settings.
Models in Django
A model is a Python class that subclasses django.db.models.Model and
defines the fields and behaviors of the data you are storing.
Each model class mapped to a single database table, and each attribute of the
model class represents a database field.
It handles the inconsistency of SQL across different platform.
Django, with ORM, makes it easier to communicate with the database, without
having to write complex SQL statements.
The models are usually located in a file called models.py.​
Key Concepts of Django Models
1. Fields: These define the data type and behavior of each attribute.
Django provides various field types such as CharField,
IntegerField, DateTimeField, ForeignKey, etc.

2. Metadata: Options for the model class to control things like default
ordering, verbose name, etc., defined in an inner class called Meta.

3. Methods: Functions that define behaviours for the data. Commonly


used methods include __str__ to define a human-readable
representation and custom methods for business logic.
Defining a Model
class Author(models.Model):
first_name = models.CharField(max_length=30) Fields
last_name = models.CharField(max_length=30)
email = models.EmailField()
headshot=models.ImageField(upload_to="/tmp")

def __str__(self):
return f"{self.first_name} {self.last_name}" Method

first_name: A character field with a maximum length of 30 characters.


last_name: A character field with a maximum length of 30 characters.
email: An email field.
__str__ method: a special method that tells Django how to display
the model’s instances as strings.
Model Fields
Fields are specified by class attributes which represents columns in the database
table (Model)
Each Field in model class should be an instance of appropriate Field class (Which
is an abstract class)
These are the things to know for creating model fields

Field Types Field Options Relationships


Common Field Types
AutoField() IntegerField() BooleanField()

• An integer field that • It stores value from - • Store true/false value


automatically 2147483648 to and generally used
increments 2147483647 for check boxes

CharField() DateField() FloatField()

• A string field for small • A date field represents • It stores floating point
to large sized strings python datetype.date number represented
instance in python by a float
instance
Common Field Types
Special EmailField()
Field
Types • A CharField that
check valid email
Relationship Field address
Types

ForeignKey() ManyToManyField() OneToOneField()


• A many to one • Defines a many to • Define a one-to-one
relationship requires many relationship with relationship
one positional another model
argument to define
related model
Field Options
- Field option are used to customize and put constraint on table rows
- Each field takes certain field specific arguments

Eg:
name = models. CharField(max_length=60)
Here "max_length" specifies the size of the VARCHAR field
class Post(models.Model):
#A field for the post title
title = models.CharField(max_length=200)
# A field for the post content
content = models.TextField()
# Automatically set the date when the post is created
created_at = models.DateTimeField(auto_now_add=True)
# Automatically set the date when the post is updated
updated_at = models.DateTimeField(auto_now=True)

# A link to the Author model


author = models.ForeignKey(Author, on_delete=models.CASCADE)

# This method tells Django to use the post title as its string
# representation
def __str__(self):
return self.title
Installing models
To use models, we need to activate them in our Django project.
This is done by adding the app to the INSTALLED_APPS list in settings.py.
Making Migrations
Now when we have described a Model in the models.py file, we must run a
command to actually create the table in the database

python manage.py makemigrations


This will generate files that describe the changes to your models.
(blogenv) D:\BLD_CSE\MyBlog>python manage.py makemigrations
Migrations for 'blogapp':
blogapp\migrations\0001_initial.py
- Create model course
- Create model student
from django.db import models

# Create your models here.


from django.db import models
from django.forms import ModelForm # Create your models here.

class course(models.Model):
courseCode=models.CharField(max_length=10)
courseName=models.CharField(max_length=50)
courseCredits=models.IntegerField()

def __str__ (self):


return self.courseCode+" "+self.courseName+" "+str(self.courseCredits)

class student(models.Model):
usn=models.CharField(max_length=10)
name=models.CharField(max_length=40)
sem=models.IntegerField()
courses=models.ManyToManyField(course,related_name='student_set')

def __str__ (self):


return self.usn+" "+self.name+" "+str(self.sem)
Applying Migrations
The table is not created yet, you will have to run one more
command, then Django will create and execute an SQL statement, based on
the content of the new file in the /migrations/ folder.
Run the migrate command:
python manage.py migrate
Which will result in this output:
(blogenv) D:\BLD_CSE\MyBlog>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, blogapp, contenttypes, sessions
Running migrations:
Applying blogapp.0001_initial... OK
Summary
Activate Models: Add your app to INSTALLED_APPS.

Validate Models: Use python manage.py check to check for errors.

Make Migrations: Use python manage.py makemigrations to create migration files.

Apply Migrations: Use python manage.py migrate to create the tables.


Working with Models - Creating Records
from studentapp.models import course,student
# Create an student
s1=student(usn='2BL21CS001',name='Harish', sem='6')
s2=student(usn='2BL21CS001',name='kumar1', sem='6')
studlist=[s1,s2,s3,s4,s5,s6] for i in studlist: i.save()
# Create a course
c1=course(courseCode='21CS61',courseName='SE',courseCredits=3)
c2=course(courseCode='21CS62',courseName='FSD',courseCredits=3)
courseList=[c1,c2,c3,c4,c5] for course in courseList: course.save()
Updating Records
# Update an author's email
from studentapp.models import student

# Step 1: Retrieve the object


stud= student.objects.get(id=1)

# Step 2: Modify the object


stud.name = 'cse_bldea'

# Step 3: Save the changes


stud.save()
Retrieving Records
Selecting Objects(Rows)
# Retrieve all objects using all().
std = student.objects.all()
# Use get() to retrieve a single object.#Get a specific author by their
first name
nm= student.objects.get(name='kumar1')

Filtering Data
# Retrieve specific objects using filter(). all posts by a specific author
nme = student.objects.filter(name=kumar1)

# Get posts containing a specific keyword in the title


keyword_student = student.objects.filter(name__contains='cse_bldea')
Field Lookups
#Use field lookups for more complex queries..
# Retrieve authors with names starting with 'O'
authors = Author.objects.filter(name__startswith='O')

Limiting Results(Slicing Data)


#Use slicing to limit the number of results.
#Retrieve the first 10 publishers
first_ten_post = Post.objects.all()[:10]

Ordering Results
# Use order_by() to sort results. Retrieve all posts ordered by name
posts = Post.objects.all().order_by('name’)
Chaining Lookups
Chaining lookups allows you to filter querysets using multiple conditions.
# Get posts by a specific author & containing a specific keyword in the
title
keyword_posts =
Post.objects.filter(author=john_doe).filter(title__contains='First’)

#Ordering Results with Chaining


auth_kPosts =
Post.objects.filter(state_province='CA').filter(name__startswith='O’)
.order_by('created_at')

Each lookup returns a new queryset, making it possible to chain multiple lookups together.
Deleting Objects
Retrieve the object you want to delete.
Call the delete() method on the object.
# Retrieve the Post object by ID
post = Post.objects.get(id=1)

# Delete the Post object


post.delete()

Deleting Multiple Objects


Use a QuerySet to filter posts by a specific date and delete them.
# Specify the date for which to delete posts
target_date = date(2023,6,1)
# Delete posts with the specified date
Post.objects.filter(created_date=target_date).delete()
Summary
Basic Retrieval: Use all() to get all objects.

Filtering: Use filter() for specific queries.

Single Object: Use get() for a single record.

Field Lookups: Use field lookups for complex queries.

Ordering and Limiting: Use order_by() and slicing.

Single Object: Use get() and delete() methods.

Multiple Objects: Use QuerySet filters and delete().


Making Changes to DB Schema

You might also like