Module5 (2)
Module5 (2)
Module5 (2)
and AJAX
Integration in
Django
Introduction
jQuery is a fast, small, and feature-rich JavaScript library. It makes things
like HTML document traversal and manipulation, event handling, and
animation much simpler with an easy-to-use API that works across a
multitude of browsers.
XMLHttpRequest (XHR):
Data Formats: While AJAX originally
XMLHttpRequest is a JavaScript object
used XML for data interchange (hence
used to interact with servers
the term "XML" in AJAX), modern
asynchronously. It is the core
applications commonly use JSON
technology behind AJAX and allows
(JavaScript Object Notation) due to its
data to be sent and received over
simplicity, lightweight nature, and
HTTP or HTTPS without refreshing the
ease of parsing in JavaScript.
entire page.
Overview of AJAX
Client-Side On the client-side (in the browser), JavaScript is
Implementati used to make asynchronous requests to the
server.
on
(JavaScript):
Typically, libraries like jQuery are used to simplify
Ajax calls, although it's also possible to use vanilla
JavaScript or other libraries/frameworks like Axios
or Fetch API.
01 02 03
In clicks or form Django views receive The response can be
Django, Ajax requests Ajax requests, in various formats,
are handled by views, process the data (if such as JSON, XML,
just like regular HTTP any), and return a HTML, or plain text,
requests. response. depending on the
requirements of the
application.
Communicatio
n between When a user interacts with a page (e.g., clicks a button),
Client and JavaScript code triggers an Ajax request.
Server:
The Ajax request is sent to a specific URL, typically
mapped to a Django view.
CSRF Protection:
REFER LAB
PROGRAM 12
Example - AJAX
in Django
JavaScript • JavaScript is a versatile and powerful programming
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
h1 {
</style>
</head>
<body>
document.addEventListener('DOMContentLoaded', function() {
button.addEventListener('click', function() {
heading.style.color = 'blue';
});
});
</script>
</body>
</html>
Introduction t • JavaScript is a high-level, interpreted programming
Variables
• Variables are used to store data values. You can declare variables
using var, let, or const.
Ex:
let name = "John"; // Using let
const age = 30; // Using const
var isStudent = true; // Using var
Data Types
• JavaScript supports various data types, including:
o Numbers: let number = 5;
o Strings: let text = "Hello";
o Booleans: let isTrue = true;
o Arrays: let fruits = ["Apple", "Banana", "Cherry"];
o Objects:
EX:
let person = {
firstName: "John",
lastName: "Doe",
age: 30
};
Functions
• Functions are blocks of code designed to perform a particular task.
function greet(name) {
return "Hello " + name;
}
if (number > 5) {
console.log("The number is greater than 5");
} else {
console.log("The number is 5 or less");
}
Loops: for, while, do-while
• An array is a special variable, which can hold more than one value:
• const cars = ["Saab", "Volvo", "BMW"];
• You access an array element by referring to the index number:
• const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0];
• This statement changes the value of the first element in cars:
cars[0] = "Opel";
Arrays are Objects
Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for a
But, JavaScript arrays are best described as arrays.
Arrays use numbers to access its "elements". In this example, person[0] returns John:
Array:
const person = ["John", "Doe", 46];
Objects use names to access its "members". In this example, person.firstName returns Jo
Object:
const person = {firstName:"John", lastName:"Doe", age:46};
Array Elements Can Be Objects
myCalculator(5, 5, myDisplayer);
• In the example above, myDisplayer is the name of a function.
• In the real world, callbacks are most often used with asynchronous functions.
• The Fetch API interface allows web browser to make HTTP requests to web servers.
• No need for XMLHttpRequest anymore.
AJAX and Fetch API
• 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.
• XML stands for eXtensible Markup Language.
• XML was designed to store and transport data.
• XML was designed to be both human- and machine-readable.
• XML is a software- and hardware-independent tool for storing and transporting data.
• What is XML?
• XML stands for eXtensible Markup Language
• XML is a markup language much like HTML
• XML was designed to store and transport data
• XML was designed to be self-descriptive
• XML is a W3C Recommendation
• This note is a note to abc from def, stored as XML:
• <note>
<to>abc</to>
<from>def</from>
<heading>Reminder</heading>
<body>Lets meet this weekend!</body>
</note>
• The XML above is quite self-descriptive:
• It has sender information
• It has receiver information
• It has a heading
• It has a message body
• But still, the XML above does not DO anything. XML is just information wrapped in tags.
• Someone must write a piece of software to send, receive, store, or display it.
The Difference Between XML and HTML
• HTTP (Hypertext Transfer Protocol) requests and responses are the foundation of
communication between clients (such as web browsers) and servers. In Django,
HttpRequest and HttpResponse are classes used to handle incoming requests from
clients and send responses back to them, respectively.
HttpRequest:
• HttpRequest represents an incoming HTTP request from a client to the Django server.
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.).
• status_code: HTTP status code of the response (200 for OK, 404 for Not Found, etc.).
• set_cookie(): Method to set cookies in the response.
• delete_cookie(): Method to delete cookies from the response.
• headers: Dictionary-like object representing response headers.
• 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:
]
• 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.
• Run the following command:
• python manage.py runserver
• Now, open your web browser and navigate to http://127.0.0.1:8000/hello/. You should
• see the text "Hello, World!" displayed in the browser, indicating that our view is successfully
handling the HTTP request and sending back the HTTP response.
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 Files:
• HTML templates in Django are regular HTML files with additional template tags and filters
provided by the Django template engine.
• 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.
• URLs and Links:
• Django's template engine provides the {% url %} template tag to generate URLs for views.
This allows you to create links dynamically in your HTML templates.
• Inheritance:
• Django templates support template inheritance, allowing you to define a base template with
common layout and structure, and then extend it in child templates to override specific
blocks.
• 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):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title> {% endfor %}
</ul>
</head>
<p>Today's date is {{ current_date|date:"F d,
<body>
Y" }}</p>
<h1>Welcome to {{ title }}</h1>
<a href="{% url 'about_page' %}">About</a>
<ul>
<img src="{% static 'images/logo.png' %}"
{% for item in items %}
alt="Logo">
<li>{{ item }}</li>
</body>
</html>
• View Function:
from django.shortcuts import render
from datetime import datetime
def index(request):
context = {
'title': "My Django App',
‘items': ['Item 1', 'ltem 2, 'Item 3],
'current_date': datetime.now(),
}
return render(request, 'index.html’, context)
• URL Configuration (urls.py):
from django.urls import path <html lang="en">
• (CSS is a stylesheet language used to style the appearance of HTML elements on web
pages.
• It allows web developers to control the layout, colors, fonts, and other visual aspects of a
website.
• 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 */
hi {
color: blue;
font-size: 24px;
text-align: center;
}
<l-- 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;
}
<l-- HTML code -->
<div class="box">Box Content</div>
CSS Flexbox and Grid Layout
• Flexbox:
• Provides a flexible way to layout elements within a container.
• Allows for dynamic alignment and distribution of space among items.
• Grid Layout:
• Defines a two-dimensional grid system for layout design.
• Allows precise positioning and alignment of elements in rows and columns.
Example:
/* CSS code */
.container {
display: flex;
justify-content: center;
align-items: center;
}
<l-- HTML code -->
<div class="container">
<div>ltem 1</div>
<div>ltem 2</div>
<div>ltem 3</div>
</div>
CSS Animations and Transitions
• Animations:
• Allows for the creation of dynamic, interactive effects on web pages.
• Keyframes define the intermediate steps of the animation.
• 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.
/* 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;
}
<l-- HTML code -->
<div class="box"></div>
Responsive Design and Media Queries
• Responsive Design:
• Ensures that web pages render well on various devices and screen sizes.
• Utilizes flexible grids, images, and CSS media queries.
• Media Queries:
• Allows for the adaptation of styles based on the characteristics of the device, such as
• screen width, height, and orientation.
Example:
/* CSS code */
@media screen and (max-width: 600px) {
.container {
flex-direction: column;
}
<|-- HTML code -->
<div class="container">
<div>ltem 1</div>
<div>ltem 2</div>
<div>ltem 3</div>
</div>
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.
• 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 APls (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.
• Here's an example of JSON data representing information about a person:
{
"name": "Mallikarjuna”,
"age": 30,
"is_student": false,
"address": {
"street": "123 Main St",
"city": "Mysuru",
"state": "CA"
},
"hobbies": ["reading”, "hiking", "coding"]
}
• Let's say we want to create a simple JSON AP| 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=20)
def to_json(self):
return {'name': self.name, 'phone’: self.phone}
• Serializer Creation (Optional):
# serializers.py
from rest_framework import serializers
from .models import Contact
class ContactSerializer(serializers.ModelSerializer):
class Meta:
model = Contact
fields = ['name’, 'phone’]
Views:
# views.py
from django.http import JsonResponse
from .models import Contact
def get_contacts(request):
contacts = Contact.objects.all()
data = [contact.to_json() for contact in contacts]
return JsonResponse(data, safe=False)
USING JQUERY Ul AUTOCOMPLETE IN DJANGO
• JQuery 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.
• 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 -->
<IDOCTYPE 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() {
alert('Button clicked!');
));
</script>
</head>
<body>
<button id="myButton">Click me</button>
</body>
</html>