Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views86 pages

Module5 (2)

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 86

Module 5: jQuery

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.

AJAX (Asynchronous JavaScript and XML) is a technique for creating fast


and dynamic web pages. AJAX allows web pages to be updated
asynchronously by exchanging small amounts of data with the server
behind the scenes.

Django is a high-level Python web framework that encourages rapid


development and clean, pragmatic design. Integrating jQuery and AJAX
with Django can make web applications more dynamic and responsive.
Importance of 1. Improved User Experience: When submitting a

Asynchronous form, the page doesn't need to reload to show


success or error messages. The message can be

Requests in displayed instantly without disturbing the user’s


current view.
django 2. Efficiency and Speed: Loading additional content
as the user scrolls down (infinite scroll) rather than
loading all content at once.
3. Reduced Server Load: Fetching and displaying
user-specific notifications or messages without
refreshing the page, thus minimizing the amount of
data transmitted.
4. Better Resource Utilization: Submitting data to
the server and allowing the user to continue
interacting with the application while the data is
being processed in the background.
Contd.. • Real-Time Updates: Applications can provide real-time
updates to users without requiring manual page
refreshes. This is especially important for applications
that require frequent updates.
• Example:
• Real-time chat applications, live sports scores, or stock
market updates.
• Enhanced Functionality
• Asynchronous requests enable more advanced
functionality and interactive features in web applications
that would be difficult or impossible to achieve with
synchronous requests.
• Example:
• Autocomplete search boxes that provide suggestions as
the user types, based on data fetched from the server.
Asynchronous Requests: AJAX
JavaScript: AJAX relies heavily on
allows web applications to send and
JavaScript to initiate requests, handle
receive data asynchronously from the
responses, and update the DOM
server without interfering with the
(Document Object Model)
display and behavior of the existing
dynamically. JavaScript frameworks
page. This means users can interact
like jQuery simplify AJAX
with the page while data is being
implementation with methods like
fetched or processed in the
$.ajax(), $.get(), and $.post().
background.

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.

JavaScript code is written to handle events, such


as button clicks or form submissions, and trigger
Ajax requests to the Django server.
Server-Side Handling (Django Views):

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.

The Django view processes the request, performs any


necessary operations (such as database queries or
computations), and generates a response.

The response is sent back to the client, where it can be


processed and used to update the DOM (Document
Object Model) dynamically, without a full page reload.
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


Updating the
manipulating HTML elements or
updating the content of specific DOM (Client-
elements on the page.
Side):
Error Error handling is an essential aspect
of Ajax development. Both client-side
Handling and and server-side code should include
mechanisms to handle errors
Validation: gracefully.

On the client-side, error callbacks


can be used to handle situations
such as netwaork errors or server-
side failures.

On the server-side, Django views


should validate input data, handle
exceptions, and return appropriate
error responses when necessary.
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 csrfmiddlewaretoken token in Ajax
requests, to ensure the security of your application.

CSRF Protection:
REFER LAB
PROGRAM 12

Example - AJAX
in Django
JavaScript • JavaScript is a versatile and powerful programming

Overview language that is primarily used for creating interactive


and dynamic content on the web. It is an essential
component of web development, alongside HTML and
CSS.
Key Characteristics of JavaScript
• Interpreted Language: JavaScript is executed by
the web browser at runtime, without prior
compilation.
• Dynamic Typing: Variable types are determined at
runtime, allowing more flexibility.
• Prototype-Based: Objects in JavaScript can inherit
properties and methods from other objects.
First-Class Functions: Functions are
treated as first-class citizens, meaning
they can be assigned to variables,
passed as arguments, and returned
from other functions.
Event-Driven: JavaScript heavily relies
on events, such as user interactions, to
execute code.
Example: Here's a complete example of an HTML file that includes JavaScript code to update the
heading text and color when a button is clicked:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Update Heading with JavaScript</title>

<style>

h1 {

color: black; /* Default color */

</style>

</head>

<body>

<h1 id="mainHeading">Original Heading</h1>

<button id="updateButton">Update Heading</button>


<script>

// Wait until the DOM is fully loaded

document.addEventListener('DOMContentLoaded', function() {

// Select the button and heading elements

const button = document.getElementById('updateButton');

const heading = document.getElementById('mainHeading');

// Add an event listener to the button

button.addEventListener('click', function() {

// Update the heading text

heading.textContent = 'Updated Heading';

// Change the heading color

heading.style.color = 'blue';

});

});

</script>

</body>

</html>
Introduction t • JavaScript is a high-level, interpreted programming

o Javascript language that's a core technology of the World Wide


Web, alongside HTML and CSS. It's an essential tool
for creating interactive and dynamic web pages.
• Client-Side Scripting Language: JavaScript is
primarily used for client-side scripting, meaning it
runs in the user's browser, allowing for dynamic
interaction without requiring server communication.
• Interpreted Language: Unlike compiled languages,
JavaScript code is executed line by line by the web
browser.
• Event-Driven: JavaScript can respond to user
actions, such as clicks, form submissions, and
keyboard inputs.
Key Features

• Syntax Similar to C: If you have experience with C, C++, or Java,


you'll find JavaScript syntax familiar.
• Lightweight and Versatile: JavaScript can be used for both simple
and complex tasks, from validating forms to creating full-fledged web
applications.
• Integrated with HTML/CSS: JavaScript works seamlessly with
HTML and CSS to enhance the user experience.
Basic Syntax

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;
}

console.log(greet("Alice")); // Output: Hello Alice


Conditional Statements
• Conditional statements allow you to perform different actions based on different
conditions.
let number = 10;

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

• Loops are used to repeat a block of code as long as a specified


condition is true.
for (let i = 0; i < 5; i++) {
console.log("This is iteration number " + i);
}
DOM Manipulation
• One of the most powerful features of JavaScript is its ability to manipulate the Document Object
Model (DOM), which represents the structure of a web page.
// Selecting an element
let element = document.getElementById("myElement");

// Changing the content of an element


element.innerHTML = "New content";

// Changing the style of an element


element.style.color = "blue";
Event Handling

• JavaScript can handle events triggered by user actions.


// Adding an event listener
let button = document.getElementById("myButton");
button.addEventListener("click", function() {
alert("Button was clicked!");
});
JavaScript Arrow Function

• Arrow functions were introduced in ES6.


• Arrow functions allow us to write shorter function syntax:
• let myFunction = (a, b) => a * b;
• Without arrow
• hello = function() {
return "Hello World!";
}
• With arrow
• hello = () => "Hello World!";
JavaScript Arrays

• 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

• JavaScript variables can be objects. Arrays are special kinds of objects.


• Because of this, you can have variables of different types in the same Array.
• You can have objects in an Array. You can have functions in an Array. You can have
arrays in an Array:
• myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
Asynchronous JavaScript

• Functions running in parallel with other functions are called asynchronous


• A good example is JavaScript setTimeout()
• function myDisplayer(something) {
document.getElementById("demo").innerHTML = something;
}

function myCalculator(num1, num2, myCallback) {


let sum = num1 + num2;
myCallback(sum);
}

myCalculator(5, 5, myDisplayer);
• In the example above, myDisplayer is the name of a function.

• It is passed to myCalculator() as an argument.

• In the real world, callbacks are most often used with asynchronous functions.

• A typical example is JavaScript setTimeout()


Waiting for a Timeout
• When using the JavaScript function setTimeout(), you can specify a callback
function to be executed on time-out:
• Example
setTimeout(myFunction, 3000);
function myFunction() {
document.getElementById("demo").innerHTML = “Hello!!";
}
In the example above, myFunction is used as a callback.
myFunction is passed to setTimeout() as an argument.
3000 is the number of milliseconds before time-out, so myFunction() will be called
after 3 seconds.
Error Handling and Debugging

• try-catch blocks: Handle errors gracefully.


• try {
• // Code that may throw an error
• } catch (error) {
• // Handle the error
• }
ES6 Features

• Template literals: Allows embedding expressions in strings.


• var name = "John";
• console.log('Hello, ${name}!’);
AJAX and Fetch API

• The Fetch API interface allows web browser to make HTTP requests to web servers.
• No need for XMLHttpRequest anymore.
AJAX and Fetch API

• Fetch API: Fetch data from a server asynchronously.


fetch('https://api.example.com/data’)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
Local Storage

• Store data locally in the browser.


• localStorage.setltem("name”, "John");
• var name = localStorage.getltem("name");
• console.log(name); // Output: John
Advanced DOM Manipulation

• Event delegation: Handling events on dynamically created elements.


document.addEventListener("click", function(event) {
if (event.target.matches("button")) {
console.log("Button clicked.");
}
)
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.
• 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

• XML and HTML were designed with different goals:


• XML was designed to carry data - with focus on what data is
• HTML was designed to display data - with focus on how data looks
• XML tags are not predefined like HTML tags are
• XML Does Not Use Predefined Tags
• XML is Extensible-Most XML applications will work as expected even if new data is
added (or removed).
• XML simplifies data sharing, data transport, platform changes and data availability
• XML Parsing and Generation:
• Django provides modules for parsing and generating XML data. The
xml.etree.ElementTree module in Python's standard library is often used for XML
parsing and generation in Django projects.
• Integration with Django Models:
• XML data can be integrated with Django models for data import/export or
synchronization with external systems. You can use Django's ORM (Object-
Relational Mapping) to query database records and serialize them into XML format.
• XML Rendering in Views:
• Django views can render XML responses using Django's HttpResponse class. This
allows you to serve XML data to clients making requests to your Django
application.
• Django Rest Framework (DRF):
• If you're building a RESTful APl with Django using Django Rest Framewaork (DRF), you have the
flexibility to serialize data into XML format alongside JSON. DRF's serializers support XML rendering
and parsing out of the box.
• XML Configuration Files:
• Django projects often use XML files for configuration purposes, such as defining URL patterns in the
urls.py file or configuring settings for third-party apps.
• Third-party Libraries:
• While Django provides basic support for handling XML data, you can also leverage thirdparty
libraries for more advanced XML processing tasks. Libraries like Ixml offer powerful XML parsing and
manipulation capabilities.
• XML-RPC and SOAP:
• Django can be used to implement XML-RPC (Remote Procedure Call) and SOAP (Simple Object
Access Protocol) APIs. These protocols use XML for data exchange between clients and servers.
• XML Schema Validation:
• Django does not natively support XML Schema validation out of the box, but you can integrate
third-party XML schema validation libraries into your Django project if needed.
• Overall, while JSON is more prevalent in web development, Django provides sufficient support
for handling XML data when required. Whether it's integrating XML with Django models,
rendering XML responses in views, or processing XML data in APls, Django offers the flexibility to
work with XML effectively within its framework.
• EXAMPLE
• Let's create a simple example demonstrating how to integrate XML handling in a Django
project. In this example, we'll create a Django app that reads data from a database and
serializes it into XML format. We'll then create a view that serves this XML data as a
response.
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()
xml_data = serialize('xml’, books)
return HttpResponse(xml_data, content_type='application/xml’)
• 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'),
]
• Database Population:
• Populate the database with some sample data using Django's admin interface or Django
shell.
• Accessing the XML Data:
• Start the Django development server (python manage.py runserver) and navigate to
http://localhost:8000/books/xml/ to access the XML data representing the books stored in
the database.
HTTPREQUEST AND RESPONSE

• 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:

from django.http import HttpResponse


def hello_world(request):
return HttpResponse("Hello, World!")
• This view function, hello_warld, takes an HttpRequest object as an argument and returns
• an HttpResponse object with the content "Hello, World!".
• Now, we need to define a URL pattern that maps to this view.
• Open myproject/urls.py and add the following code:
from django.urls import path
from myapp.views import hello_world
urlpatterns =[
path('hello/', hello_world, name="hello_world’),

]
• 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">

from myapp.views import index <head>


<meta charset="UTF-8">
urlpatterns =
<title>About Us</title>
path(", index, name='index’),
</head>
]
<body>
Static Files:
<h1>About Us</h1>
Place static files (e.g., logo.png) in the myapp/static/ directory.
<p>This is the about page of our Django app.</p>
Link to About Page (myapp/templates/about.html):
<a href="{% url 'index' %}">Back to Home</a>
<IDOCTYPE html|> </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.
CSS
Cascading Style Sheets (CSS):

• (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.

• Some key features and benefits of jQuery:


• DOM Manipulation: jQuery provides an easy-to-use API| for selecting and manipulating HTML
elements in the Document Object Model (DOM). With jQuery, you can easily traverse the DOM
tree, modify element attributes and content, an add or remove elements from the page.
• Event Handling: jQuery simplifies event handling by providing methods for attaching event
listeners to HTML elements. You can handle user interactions such as clicks, mouse
movements, keyboard inputs, and more with ease.
• AJAX Support: jQuery simplifies asynchronous HTTP requests (Ajax) by providing a set of
methods for making requests to the server and handling server responses. This allows you
to load data from the server without refreshing the entire web page, leading to a more
responsive user experience.
• Animation Effects: jQuery includes built-in animation effects and methods for creating
custom animations. You can animate CSS properties, show/hide elements with various
effects, and create complex animations with ease.
• Cross-browser Compatibility: jQuery abstracts away many browser inconsistencies and
provides a unified interface that works across different web browsers. This helps developers
write code that behaves consistently across various browser environments.
• Extensibility: jQuery is highly extensible, allowing developers to create plugins to extend
its functionality further. There is a vast ecosystem of jQuery plugins available for various
purposes, ranging from Ul components to complex data visualization tools.
• Overall, jQuery simplifies JavaScript development and makes it easier to create dynamic,
interactive, and responsive web applications.
let's create a simple Django project from scratch and integrate jQuery step by step.

• 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>

You might also like