FSD Module-5
FSD Module-5
Module-05
jQuery and AJAX Integration in Django
pg. 1
FSD MODULE 5
Once the response is received from the server, JavaScript code on the client-
side processes it.
Depending on the content of the response, the DOM may be updated to
reflect changes, display new data, or show error messages.
This process typically involves manipulating HTML elements or updating the
content of specific elements on the page.
pg. 2
FSD MODULE 5
CSRF Protection:
When using Ajax with Django for POST requests, it's crucial to protect against
Cross-Site Request Forgery (CSRF) attacks.
Django provides built-in CSRF protection mechanisms, such as (% csrf_token
%) template tag or csrf middleware token in Ajax requests, to ensure the
security of your application.
pg. 3
FSD MODULE 5
JavaScript
• Ajax, running JavaScript as its engine. Your application will have JavaScript
working with
o XMLHttpRequest
o JavaScript working with HTML, XHTML, or HTML5;
pg. 4
FSD MODULE 5
pg. 5
FSD MODULE 5
• The XMLHttpRequest object is the reason why the kind of games that can be
implemented with Ajax technologies do not stop at clones of Tetris and other
games that do not know or care if they are attached to a network.
• They include massive multiplayer online role-playing games where the network
is the computer.
• With XMLHttpRequest, "Ajax chess" is more likely man-to-man chess against
another human player connected via the network.
• The XMLHttpRequest object is the object that lets Gmail, Google Maps, Bing
Maps, Facebook, and many less famous Ajax applications deliver on Sun's
promise: the network is the computer.
• There are differences and some incompatibilities between different versions of
XMLHttpRequest, and efforts are underway to advance "level-2-compliant"
XMLHttpRequest implementations, featuring everything that is expected of an
XMLHttpRequest object today and providing further functionality in addition,
somewhat in the spirit of level 2 or level 3 CSS compliance.
• We will not be looking at level 2 efforts, but we will look at the baseline of
what is expected as standard in most XMLHttpRequest objects.
• The basic way that an XMLHttpRequest object is used is that o the object is
created or reused o a callback event handler is specified o the connection is
opened o the data is sent, and then o when the network operation completes,
the callback handler retrieves the response from XMLHttpRequest and takes an
appropriate action.
Methods
• A bare-bones XMLHttpRequest object have the following methods.
1. XMLHttpRequest.abort() This cancels any active request.
2. XMLHttpRequest.getAllResponseHeaders() This returns all HTTP response
headers sent with the response
pg. 6
FSD MODULE 5
Properties
• A bare-bones XMLHttpRequest object have the following properties:
1. XMLHttpRequest.onreadystatechange XMLHttpRequest.readyState
XMLHttpRequest.onreadystatechange, which is called without argument each
time the ready state of XMLHttpRequest changes.
An XMLHttpRequest object can have five ready states:
i. Uninitialized - meaning that open() has not been called.
ii. Open - open() has been called but send() has not.
iii. Sent - send() has been called, and headers and status are available, but the
response is not yet available.
iv. Receiving - the response is being downloaded and responseText has the
portion that is presently available.
v. Loaded, meaning that the network operation has completed. If it has
completed successfully (that is, the HTTP status stored in
pg. 7
FSD MODULE 5
Define URLs:
Configure the URL patterns to route requests to the appropriate views.
pg. 8
FSD MODULE 5
#ajax_example/urls.py
from django.urls import path
from ajax_app import views
urlpatterns = [
path(", views.index, name='index'),
path('ajax_submit/', views.ajax_submit, name='ajax_submit'),]
Create Templates:
Create HTML templates for the index page and the success page.
<l-ajax_app/templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax Form Submission</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script></head>
<body>
<h1>Ajax Form Submission</h1>
<form id="ajax-form">
<label for="input-data">Enter Data:</label>
<input type="text" id="input-data" name="input_data">
<button type="submit">Submit</button>
</form>
<div id="result"></div>
<script src="{% static 'ajax_app/js/main.js' %}"></script>
</body>
</html>
pg. 9
FSD MODULE 5
});
Define Views:
Define Django views to handle the form submission.
#ajax_app/views.py
from django.shortcuts import render
from django.http import JsonResponse
def index(request):
return render(request, 'ajax_app/index.html')
def ajax_submit(request):
pg. 10
FSD MODULE 5
Client-Side Scripting: JavaScript primarily runs on the client-side (in the user's
web browser), unlike server-side languages like Python (used in Django). This
means JavaScript code is executed on the user's device, allowing for real-time
interaction without needing to communicate with the server for every action.
pg. 11
FSD MODULE 5
Browser Compatibility: JavaScript code can run on most modern web browsers,
including Chrome, Firefox, Safari, and Edge. However, developers need to
consider browser compatibility and may need to use polyfills or feature
detection to ensure consistent behavior across different browsers.
pg. 12
FSD MODULE 5
malicious scripts are injected into web pages. Proper input validation, output
encoding, and secure coding practices are essential for mitigating these risks.
Overall, JavaScript is a fundamental technology for web development,
empowering developers to create interactive and engaging web applications
that enhance the user experience
Example:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<h1 id="heading">Hello, World!</h1>
<button id="change-text">Change Text</button>
<script>
// JavaScript code to handle button click event and modify the heading text
document.getElementById("change-text").addEventListener("click", function() {
var heading document.getElementById("heading");
heading.textContent = "Text Changed!";
heading.style.color = "red";
));
</script>
</body></html>
In this example:
HTML defines a heading and a button.
JavaScript code adds an event listener to the button, which changes the
heading text and color wihen clicked.
pg. 13
FSD MODULE 5
The textContent property is used to modify the text content of the heading
element.
The style property is used to modify the CSS style of the heading element.
Introduction to JavaScript
JavaScript is a scripting language primarily used for client-side web
development.
It was developed by Brendan Eich at Netscape Communications in 1995.
JavaScript is used to add interactivity and dynamic behavior to web pages.
Control Structures
Conditional statements: if, else if, else.
var age = 18;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
pg. 14
FSD MODULE 5
Functions
Functions are blocks of reusable code.
function greet(name) {
Arrow functions:
var add = (a, b) => a + b;
console.log(add(2, 3)); // Output: 5
DOM Manipulation
DOM represents the structure of HTML documents.
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!"); });
pg. 15
FSD MODULE 5
ES6 Features
Template literals: Allows embedding expressions in strings.
var name = "John";
console.log('Hello, S(name)!');
Asynchronous Programming
Promises: Handle asynchronous operations.
var promise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve("Data fetched successfully.");
}, 2000);
});
promise.then(function(data) {
console.log(data);
pg. 16
FSD MODULE 5
});
Local Storage
Store data locally in the browser. localStorage.setItem("name", "John");
var name = localStorage.getItem("name");
console.log(name); // Output: John
Object-Oriented JavaScript
Prototypes and inheritance: Define methods shared among objects.
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() { return "Hello, " + this.name + "I";
};
var john = new Person("John");
pg. 17
FSD MODULE 5
console.log(john.greet());
Module Systems
ES6 modules: Organize and share code across files.
//math.js
export function add(a, b) {
return a + b;
//app.js
import (add) from './math.js';
console.log(add(2, 3)); // Output: 5
Web APIs
Geolocation API: Retrieve the user's location.
navigator.geolocation.getCurrentPosition(function(position) {
console.log("Latitude:", position.coords.latitude);
console.log("Longitude:", position.coords.longitude); });
Performance Optimization
Minification: Reduce file size by removing unnecessary characters.
Code splitting: Split code into smaller chunks to improve loading times.
pg. 18
FSD MODULE 5
XML
In Django, XML (eXtensible Markup Language) can be used for various purposes,
such as data interchange, configuration files, or representing structured data.
While JSON (JavaScript Object Notation) is more commonly used for data
interchange in web applications due to its lightweight and easy-to-read format,
Django does provide facilities for handling XML data when needed.
pg. 19
FSD MODULE 5
If you're building a RESTful API with Django using Django Rest Framework (DRF)
vou have the flexibility to serialize data into XML format alongside JSON. DRF's
serializers support XML rendering and parsing out of the box.
Third-party Libraries:
While Django provides basic support for handling XML data, you can also
leverage third- party libraries for more advanced XML processing tasks. Libraries
like Ixml offer powerful XML parsing and manipulation capabilities.
pg. 20
FSD MODULE 5
Model Definition:
Define a Django model in models.py representing the data you want to serialize.
#xml_example/models.py
from django.db import models
class Book(models.Model):
title= models. CharField(max_length=100)
author= models. CharField(max_length=100)
published_date = models.DateField()
def_str_(self):
return self.title
View Implementation:
Create a Django view in views.py that fetches data from the database and
serializes it Into XML format.
#xml_example/views.py
from django.http import HttpResponse
from django.core.serializers import serialize
from models import Book
def books xml(request):
books Book.objects.all()
pg. 21
FSD MODULE 5
URL Configuration:
Map the view to a URL in urls.py.
#xml_example/urls.py
from django.urls import path
from .views import books_xml
urlpatterns = [ path('books/xml/', books_xml, name='books_xml'),
1
Database Population:
Populate the database with some sample data using Django's admin interface or
Django shell.
This example demonstrates how to serialize Django model data into XML format
and serve it as a response using a Django view. You can extend this example by
customizing
the XML serialization, adding more fields to the model, or incorporating XML
parsing for handling XML data received from clients.
pg. 22
FSD MODULE 5
It contains metadata about the request, such as headers, request method, URL,
query parameters, POST data, etc.
Attributes:
method: HTTP method used for the request (GET, POST, PUT, DELETE, etc.).
path: Path portion of the requested URL.
GET: Dictionary-like object containing query parameters from the URL.
POST: Dictionary-like object containing POST data sent in the request body.
META: Dictionary containing metadata about the request (headers, IP
address, user agent, etc.).
Usage:
HttpRequest objects are passed as the first argument to Django view functions.
Views access request data through attributes like GET, POST, and META.
HttpResponse:
HttpResponse represents an HTTP response sent from the Django server to the
client.
It contains the response content, status code, and headers.
Attributes/Methods:
content: Content of the response (HTML, JSON, XML, etc.).
pg. 23
FSD MODULE 5
status_code: HTTP status code of the response (200 for OK, 404 for Not
Found, etc.).
Usage:
Django views return HttpResponse objects to send responses back to clients.
HttpResponse objects can be customized with response content, status code, and
headers.
Example:
let's create a simple Django project from scratch and implement a view that
handles an HTTP request and sends back an HTTP response.
First, ensure you have Django installed. If not, you can install it via pip:
pip install django
Now, let's create a new Django project and app:
django-admin startproject myproject
cd myproject
python manage.py startapp myapp
Next, let's define a view that handles an HTTP request and sends back a simple
HTTP response.
Open myapp/views.py and add the following code:
from django.http import HttpResponse
def hello_world(request):
return HttpResponse("Hello, World!")
pg. 24
FSD MODULE 5
This maps the URL/hello/ to the hello_world view function we defined earlier.
Finally, let's run the Django development server and test our view.
HTML
let's provide a quick glance at how HTML is used in conjunction with Django to
create dynamic web pages:
Template System:
Django comes with a powerful template engine that allows you to build HTML
templates with placeholders for dynamic data.
HTML Template File
HTML templates in Django are regular HTML files with additional template tags
and filters provided by the Django template engine.
pg. 25
FSD MODULE 5
Template Tags:
Template tags are enclosed in (%%) and allow you to add logic and control flow
to your templates. For example, (% if %}, {% for %), (% include %), etc.
Template Filters:
Template filters are enclosed in {{ )} and allow you to modify the output of
template variables. For example, {{ variable | default:"No data"}}, {{ variable |
date:"Y-m-d" )), etc.
Context Data:
Context data is passed from views to templates and contains dynamic data that
will be rendered in the HTML. Views render templates with context data using
the render() function.
Static Files:
Static files such as CSS, JavaScript, Images, etc., can be included in Django
templates using the (% static %) template tag. These files are served by Django's
static file server during development.
Forms:
Django provides form handling functionalities that generate HTML form elements
in templates. Forms can be rendered manually or by using Django's form
rendering helpers.
Inheritance:
pg. 26
FSD MODULE 5
HTML Escaping:
Django automatically escapes HTML special characters in template variables to
prevent XSS (Cross-Site Scripting) attacks. Use the safe filter to mark a string as
safe HTML if necessary.
Example:
Let's create a simple example to illustrate how HTML is used with Django
templates:
Template File (myapp/templates/index.html):
<IDOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<h1>Welcome to {{ title }}</h1>
<ul>
{% for item in items %)
<li>{{
item }}
{% endfor %)
</ul>
<p>Today's date is {{ current_date | date:"F d, Y" }}</p>
pg. 27
FSD MODULE 5
View Function:
from django.shortcuts import render
from datetime import datetime
def index(request):
context = {
'title': 'My Django App',
'items': ['Item 1', 'Item 2', 'Item 3
'current_date': datetime.now(),
}
return render(request, 'index.html', context)
Static Files:
Place static files (e.g., logo.png) in the myapp/static/directory.
Link to About Page (myapp/templates/about.html):
<!DOCTYPE html>
<html lang=en >
<head>
<meta charset="UTF-8">
<title>About Us</title>
pg. 28
FSD MODULE 5
</head>
<body>
<h1>About Us</h1>
<p>This is the about page of our Django app.</p>
<a href="(% url 'index' %)">Back to Home</a>
</body>
</html>
In this example, we have a base template index.html that renders dynamic data
such as the title, a list of items, the current date, and a link to the about page.
We use template tags like (% for %), (% url %), and (% static %) to generate
dynamic content and links. The view function retrieves data and renders the
template with the context data.
Key Concepts:
Selectors: Used to target HTML elements for styling.
Properties: Define the visual characteristics of the selected elements.
Values: Specify the desired settings for the properties.
Example:
/* CSS code */
h1 {
color: blue;
font-size: 24px;
pg. 29
FSD MODULE 5
text-align: center;
<-- HTML code -->
<h1>This is a Heading</h1>
CSS Selectors and Box Model
Selectors:
Element Selector: Targets HTML elements by their tag name.
Class Selector: Targets elements with a specific class attribute.
ID Selector: Targets a single element with a unique ID attribute.
Descendant Selector: Targets elements that are descendants of a specified
parent.
Pseudo-classes: Targets elements based on their state or position.
Box Model:
Content: The actual content of the element.
Padding: Space between the content and the border.
Border: The border surrounding the padding.
Margin: Space outside the border, separating the element from other
elements.
Example:
/* CSS code */
.box {
width: 200px;
height: 100px;
padding: 20px;
border: 2px solid black;
margin: 10px;
pg. 30
FSD MODULE 5
Grid Layout:
Defines a two-dimensional grid system for layout design.
Allows precise positioning and alignment of elernents in rows and columns.
Example:
/* CSS code */
container (
display: flex;
justify-content: center;
align-items: center;
}
pg. 31
FSD MODULE 5
Transitions:
Smoothly animates the transition of an element's property from one state to
another.
Transition properties include duration, timing function, delay, and property
to transition.
Example:
/* CSS code */
@keyframes slide {
0% { transform: translateX(0); }
100% { transform: translateX(100px); }
.box {
width: 100px;
height: 100px;
background-color: blue;
animation: slide 2s infinite alternate;
<!-- HTML code -->
<div class="box"></div>
Media Queries:
Allows for the adaptation of styles based on the characteristics of the device,
such as screen width, height, and orientation.
pg. 32
FSD MODULE 5
Example:
/* CSS code */
@media screen and (max-width: 600px) {
.container {
flex-direction: column;
}
<!-- HTML code ->
<div class="container">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
</div>
Example: simple example of a phone directory web application using Django for
the backend and HTML/CSS/JavaScript for the frontend.
First, make sure you have Django installed. You can install it via pip:
pip install django
Create a new Django project:
django-admin startproject phone_directory
Create a Django app within the project:
cd phone_directory
django-admin startapp directory
pg. 33
FSD MODULE 5
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.cs
s">
</head>
pg. 34
FSD MODULE 5
<body>
<div class="container">
<h1>Phone Directory</h1>
<ul>
{% for contact in contacts %}
<li>{{ contact.name}} - {{ contact.phone }}<
/li>
{% endfor %}
</ul>
</div>
</body>
</html>
Now, let's move to the frontend part:
Create a CSS file styles.css in phone directory/static/css:
CSS
/* styles.css */
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.container {
max-width: 800px;
margin: 20px auto;
padding: 20px;
background-color: #fff;
border-radius: 5px;
pg. 35
FSD MODULE 5
{margin-bottom: 10px;
}
And you should be able to see your phone directory application running at
http://127.0.0.1:8000/. You can then add more features like adding new
contacts, editing existing contacts, etc., based on your requirements.
JSON
JSON (JavaScript Object Notation) is a lightweight data interchange format that is
easy for humans to read and write and easy for machines to parse and
generate. It is based on a subset of the JavaScript programming language, but
it's language-independent, meaning it can be used with most programming
languages.
pg. 36
FSD MODULE 5
JSON is commonly used for transmitting data between a server and a web
application as an alternative to XML. It's widely used in web development for
APIs (Application Programming Interfaces) because it’s simple, easy to
understand, and lightweight.
JSON data is represented as key-value pairs, similar to python dictionaries or
Javascript objects. The keys are strings, and the values can be strings, numbers,
arrays, objects, booleans, or null.
In this example:
"name", "age", and "is_student" are key-value pairs with string keys and
string or boolean values.
"address" is a key-value pair where the value is another object containing
keys: "street", "city", and "state".
"hobbies" is a key-value pair where the value is an array containing strings.
JSON data can be parsed and converted into native data types in most
programming languages, making it easy to work with in a variety of contexts.
pg. 37
FSD MODULE 5
simple example:
Let's say we want to create a simple JSON API for managing contacts.
Model Setup:
# models.py
from django.db import models
class Contact(models.Model):
name = models. CharField(max_length=100)
phone models CharField(max length=201
def to_json(self):
return {'name': self.name, 'phone': self.phone}
Views:
# views.py
from django.http import JsonResponse
pg. 38
FSD MODULE 5
URL Configuration:
# urls.py
from django.urls import path
from.views import get_contacts
urlpatterns = [
path('contacts/', get_contacts, name='get_contacts'),
With this setup, when you visit http://127.0.0.1:8000/contacts/, you'll receive a
JSON response containing all the contacts in the database.
Make sure to install Django Rest Framework (pip install django rest framework) if
you choose to use serializers from it. Also, don't forget to include the app in
your Django project's INSTALLED_APPS setting and set up your database.
Query is a fast, small, and feature-rich JavaScript library. It simplifies various tasks
like HTML document traversal and manipulation, event handling, animation,
and Ajax interactions for web development. jQuery was created by John Resig in
2006 and has since become one of the most popular JavaScript libraries used by
developers worldwide.
pg. 39
FSD MODULE 5
pg. 40
FSD MODULE 5
Define a View:
In myapp/views.py, define a simple view that renders a template.
from django.shortcuts import render
def index(request):
return render(request, 'myapp/index.html')
Create a Template:
Create a directory named templates in the myapp directory. Inside templates,
create a file named index.html.
html
<!-- myapp/templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Django with jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script
$(document).ready(function() {
// Example: Alert message on button click
$('#myButton').click(function() {
pg. 41
FSD MODULE 5
alert('Button clicked!');
}};
}};
< /Scripts>
</head>
<body>
<button id="myButton">Click me</button>
</body>
</html>
Define URLs:
In myproject/urls.py, define a URL pattern to map to the view.
from django.urls import path
from myapp.views import index
urlpatterns = [
path(", index, name='index'),
Run the Server:
python manage.py runserver
Visit http://127.0.0.1:8000/ in your browser, and you should see a button. When
you click the button, it should display an alert message, demonstrating the use
of jQuery.
This setup demonstrates the integration of jQuery with Django from scratch. You
can further expand the project by adding more views, templates, and jQuery
functionality as needed for your application.
*****************************************************************
pg. 42