FulStack-module1,2 (1)
FulStack-module1,2 (1)
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.
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.
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.
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.
{% 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.
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.
Filter : {{ text|addslashes }}
escape: Escapes special HTML characters to ensure the text is safe for HTML rendering. This
is crucial for preventing XSS (Cross-Site Scripting) attacks.
<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 content %}
{% 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 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
2. Metadata: Options for the model class to control things like default
ordering, verbose name, etc., defined in an inner class called Meta.
def __str__(self):
return f"{self.first_name} {self.last_name}" Method
• 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
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)
# 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
class course(models.Model):
courseCode=models.CharField(max_length=10)
courseName=models.CharField(max_length=50)
courseCredits=models.IntegerField()
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')
Filtering Data
# Retrieve specific objects using filter(). all posts by a specific author
nme = student.objects.filter(name=kumar1)
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’)
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)