0% found this document useful (0 votes)
19 views

Django

django web development

Uploaded by

amallalu42
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Django

django web development

Uploaded by

amallalu42
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Web development using Django

Django is a high-level, open-source web framework written in Python that


follows the Model-View-Template (MVT) architectural pattern.
Developed with the goal of making web development faster, easier, and more
robust, Django provides a set of tools and conventions that streamline common
tasks, allowing developers to focus on building web applications rather than
dealing with low-level details.

When we talk about server side and client side in the context of web
development, we are referring to the division of tasks between the
server and the client
Serverside
The server is responsible for processing requests, managing
the application logic, interacting with the database, and
generating dynamic content.
In a Django application, the server-side components include
the models, views, and the business logic implemented in
Python.
Server-side processing occurs on the web server before the
content is sent to the client
Client side
The client is the user's browser, which is responsible for rendering the content,
handling user interactions, and managing the presentation layer.
In a Django application, the client-side components include HTML, CSS which are
responsible for rendering the UI and handling user interactions.

Client-side proces occurs on the user's device after receiving the


content from tsinghe server.
In summary, Django handles the server-side logic, processing
requests, interacting with the database, and generating dynamic
content.
The client-side, on the other hand, deals with rendering the content
in the browser and handling user interactions. Together, they form a
full-stack web application
HTML
HTML, or HyperText Markup Language, is the standard markup language for
creating web pages. It is used to structure content on the web and is an essential
building block of any web development project. HTML provides a set of elements or
tags that define the structure and content of a web page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Your Page Title</title>
</head>
<body>
<!-- Content goes here -->
</body>
</html>
In HTML, a web page is typically structured into main parts that define its overall layout and
content. Here are the main parts of an HTML document:

Document Type Declaration:

<!DOCTYPE html>
Declares the document type and version of HTML. This declaration ensures that the browser
interprets the document correctly.

HTML Element:

<html lang="en">
The root element of an HTML document. The lang attribute specifies the language of the
document.
Head Element:
<head>
<!-- Meta information, links to stylesheets, and other head elements -->
</head>

Contains meta-information about the HTML document, such as character set, title,
and links to external resources

Meta Charset and Viewport:

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

Specifies the character set and sets the viewport for responsive design.
Title Element:
<title>Your Page Title</title>

Defines the title of the HTML document, which appears in the browser's title bar or
tab.
Body Element:

<body>
<!-- Content of the HTML document -->
</body>

Contains the content of the HTML document, including text, images, links, forms,
etc.
Headings:

<h1>This is a Heading 1</h1>


<h2>This is a Heading 2</h2>
<!-- ... -->
Defines headings of various levels, indicating the structure of the content.
Paragraphs:

<p>This is a paragraph.</p>
Represents a paragraph of text.
Lists:
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
<ol>
<li>Item 1</li>
<li>Item 2</li>
</ol>
Defines unordered (bulleted) and ordered (numbered) lists
Links:

<a href="https://www.example.com">Visit Example.com</a>


Creates hyperlinks to other web pages or resources.

Images:

<img src="image.jpg" alt="Description">

Embeds images in the document.

Forms:

<form action="/submit" method="post">


<!-- Form fields, labels, and submit button -->
</form>
Defines an HTML form for user input.
Divisions and Spans:

<div class="container">
<!-- Content inside a div -->
</div>

<p>This <span style="color: red;">word</span> is red.</p>

<div> is used for grouping and applying styles, while <span> is used for inline styling

Comments:

<!-- This is a comment -->

Allows developers to add comments for documentation or clarification.


CSS
CSS, or Cascading Style Sheets, is a style sheet language used for
describing the presentation of a document written in HTML or XML. CSS
defines how elements on a web page should be displayed, including their
layout, colors, fonts, and other visual properties. Here's an overview of key
concepts and examples in CSS

selector {
property: value;
}
To add CSS styles to an HTML document, you have a few different options. Here are three common
methods:

1. Inline Styles:

Inline styles are added directly to the HTML elements using the style attribute.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inline Styles Example</title>
</head>
<body>
<h1 style="color: blue; text-align: center;">Hello, World!</h1>
<p style="font-size: 16px; margin-top: 20px;">This is a paragraph with inline styles.</p>
</body>
</html>
2. Internal Styles:
Internal styles are defined within the <style> tag in the HTML document's <head>
section.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Internal Styles Example</title>
<style>
h1 {
color: blue;
text-align: center;
}
p{
font-size: 16px;
margin-top: 20px;
}
</style>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph with internal styles.</p>
</body>
</html>
3. External Styles:
External styles are defined in a separate CSS file, and the HTML document links to
this file using the <link> tag.

styles.css:

/* styles.css */
h1 {
color: blue;
text-align: center;
}

p{
font-size: 16px;
margin-top: 20px;
}
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>External Styles Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph with external styles.</p>
</body>
</html>

Using external styles is generally preferred for better organization and maintainability,
especially when working on larger projects.

Choose the method that best fits your needs and the scale of your project. Keep in
mind that good separation of concerns (HTML for structure, CSS for styling) is a best
practice for web development.
JAVA SCRIPT

JavaScript: JavaScript is a programming language


that adds interactivity and dynamic behavior to web
pages. It is commonly used for client-side scripting,
enabling features like form validation, animations,
and updating content without requiring a page
reload.
JavaScript in <head> or <body>

You can place any number of scripts in an HTML document.


Scripts can be placed in the <body>, or in the <head> section of an HTML
page, or in both.

JavaScript in <head>

In this example, a JavaScript function is placed in the <head> section of an


HTML page.
The function is invoked (called) when a button is clicked:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph
changed.";
}
</script>
</head>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
JavaScript in <body>

In this example, a JavaScript function is placed in the <body> section of an


HTML page.
The function is invoked (called) when a button is clicked:
<!DOCTYPE html>
<html>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
External JavaScript

Scripts can also be placed in external files:

External file: myScript.js

function myFunction() {
document.getElementById("demo").innerHTML =
"Paragraph changed.";
}
<!DOCTYPE html>
<html>
<body>

<h2>External JavaScript</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p>(myFunction is stored in an external file called "myScript.js")</p>

<script src="myScript.js"></script>

</body>
</html>
Bootstrap
Bootstrap is a popular open-source front-end framework that allows
developers to build responsive and visually appealing web pages quickly. It
includes a set of pre-designed components, such as navigation bars,
buttons, forms, and typography styles, making it easier to create a
consistent and professional-looking user interface.
Here are the key points about Bootstrap:
Installation:
You can include Bootstrap in your project by adding the Bootstrap CSS and
JavaScript files to your HTML document. You can either download Bootstrap
and host it locally or include it from a CDN (Content Delivery Network). For
example, including Bootstrap from a CDN in your HTML file:
<!-- Add this to the head of your HTML file -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></
script>

Grid System:
Bootstrap's grid system is responsive and allows you to create layouts that
adapt to different screen sizes. It is based on a 12-column grid system,
making it easy to create flexible and responsive designs.
Components:
Bootstrap provides a wide range of pre-styled components that you can
use in your project. These include navigation bars, buttons, forms,
cards, modals, carousels, and more. You can easily customize these
components to suit your design requirements.
Responsive Design:
Bootstrap is designed to be mobile-first and includes responsive CSS
classes that help in creating websites that look good on various devices,
from small mobile screens to large desktop monitors.

Documentation:
Bootstrap has extensive documentation that provides detailed
information on all its components, utilities, and features. The official
Bootstrap documentation is a valuable resource for learning and
reference
Utilities:
Bootstrap includes utility classes that can be applied directly to HTML
elements to achieve common styling or layout adjustments. For example,
classes like text-center, m-2 (margin), p-3 (padding), etc
Django
Django is a high-level web framework written in Python that
encourages rapid development and clean, pragmatic design. It
follows the Model-View-Controller (MVC) architectural pattern but
refers to it as the Model-View-Template (MVT) pattern. Django
provides a set of tools and conventions to help developers build web
applications quickly and efficiently.

Model: This represents the data structure of your application. Models


define the database schema, including tables and relationships between
them. Django's Object-Relational Mapping (ORM) system allows you to
interact with the database using Python code rather than raw SQL.
View: Views handle the logic of processing user requests and
returning appropriate responses. They receive input from the user,
interact with the model to retrieve or manipulate data, and then pass
that data to the template for rendering
Forms: Django provides a form-handling system to ease the process
of collecting and validating user input. Forms are defined in Python and
can be easily rendered in templates. They also handle data validation
and can be tied directly to models for data persistence.

Admin Site: Django includes a built-in administration site that allows


developers and administrators to manage the data in the application
without directly interacting with the database or writing custom views.
Virtual environment

A virtual environment in Python is a self-contained


directory that houses a Python interpreter along with its
standard library and other support files. It allows you to
create isolated environments for your Python projects,
ensuring that the dependencies and packages used by
one project do not interfere with those of another. This is
particularly useful when working on multiple projects with
different requirements.
Create a virtual environment
python -m venv myenv
What is a project folder
In Django, a project folder is you start a new Django project
using the django-admin startproject command. The project
folder typically includes various files and subdirectories that
collectively form the foundation of your web application.
Project Configuration File (settings.py): This file contains the
configuration settings for your Django project. It includes database
settings, time zone, static files configuration, middleware settings,
installed applications, and more. Developers often modify this file to
customize the behavior of their Django project .
Root URL Configuration (urls.py): The urls.py file in the
project folder defines the top-level URL patterns for your entire
Django project. It acts as a central routing mechanism that
directs requests to the appropriate views within the project.
Run the Django Project

Now that you have a Django project, you can run it, and see what it looks
like in a browser.
Navigate to the /myproject folder and execute this command in the
command prompt:

py manage.py runserver
Django Create App
What is an App?
An app is a web application that has a specific meaning in your project, like a home page, a contact form, or a
members database.
In this tutorial we will create an app that allows us to list and register members in a database.
But first, let's just create a simple Django app that displays "Hello World!".
Create App
I will name my app members.
Start by navigating to the selected location where you want to store the app, and run the command below.
If the server is still running, and you are not able to write commands, press [CTRL] [BREAK] to stop the server and
you should be back in the virtual environment.

py manage.py startapp members

Django creates a folder named members in my project, with this content:

myproject
manage.py
myproject/
members/
migrations/
__init__.py
Templates
Create a templates folder inside the (your appname)folder, and create a HTML file named
(your filename.html)
The file structure should be something like this:

myproject
myproject
manage.py
myproject/
appname/
templates/
Myfirst.html
Myfirst.html
If you want to specify the location of your templates in the settings.py file of your Django project, you can do so by
setting the TEMPLATES configuration. Django, by default, looks for templates in the "app_name/templates/"
directory. However, if you want to customize this behavior, follow these steps:

Open the settings.py file in your Django project.

Locate the TEMPLATES configuration. It's a list of dictionaries, and one of the dictionaries contains the
'APP_DIRS': True setting, which means Django will look for templates in the "app_name/templates/" directory.

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
# ...
},
]
If you want to add additional directories to search for templates, you can add them to the 'DIRS' list. For example, to
include a project-level templates directory, you can do:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')], # Add this line
'APP_DIRS': True,
# ...
},
]
Make sure to import the os module at the beginning of your settings.py file:

import os

Replace 'templates' with the name of your desired templates folder.

Save the settings.py file.

Now, Django will look for templates in both the app-specific templates directory and the project-level templates
directory. This allows you to organize your templates in a way that suits your project structure.

Remember to run,
python manage.py runserver

again if your development server is not running to see the changes.


Static files
In Django, static files are the assets like CSS, JavaScript, images, and other files that are served directly to the
client without any processing by the server. These files are typically used to style the web pages, add
interactivity, and include other resources necessary for the presentation layer of your application.

To handle static files in Django, you can follow these steps:

Configure Static Files Settings:


In your settings.py file, make sure you have the following settings configured:
# settings.py

# Static files (CSS, JavaScript, images)

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static’)]

STATIC_URL is the URL prefix for static files, and


STATICFILES_DIRS is a list of directories where Django will look
for static files.
Project hosting
Uploading a project to Python Anywhere involves several steps. Python Anywhere is a
cloud service that provides a Python
environment capable of running web apps and scripts. 1. Create a python Anywhere
Accounts. 2. Log in to Python Anywhere Dashboard . 3. Open vs code to create text
file. Vs code

Text file

Pip freeze

Requirement.txt
4. Then go to project folder and compress zip. 5. Go to Python Anywhere then click
files then upload the
6. Open a Bash console . ↓
Ls

Unzip project folder.zip

Clear

Ls

Cd project folder name

Clear
7. Setting up a Virtual Environment in python Anywhere.
click→Help→deploying an existing Django project on python
Anywhere.
8. According to previous step there is a code and paste it to

bash console and change the name of virtual environment.


$ Mk virtual environment python--/--/mydata(env).

Then virtual environment is created.


9. Ls (we can see the all files in that folder).
10. Pip install -r requirement.txt (when complete →clear).
11. Go to web in Python Anywhere .
12. Add a new web app and give the path to the source code.
Source code : /home/user name/project folder. Copy from the
manage.py file in Python Anywhere
Virtual env : (give path)
/home/user name/.virtualenvs/our environment name. Copy it from
the
13. Click →WSGI configuration file.
14. Then update the code.by delete the other and place only
Django code and then update that code.  Uncommand Import ,path(give your
path),/home/user
name/project name.  Uncommand lf .OS.environ--(change previous project name)
 Save→ web page→reload→open link
15. Go to setting.py(update code)
Setting.py

Allowed Hosts =[‘username.pythonAnywhere’]

Save

Reload

Click lin
16. Go to settings.py
Setting.py

Templates

DIRS:[BASE_DIR/’template’]

Reload

Click link
17. Go to Static File web in Python Anywhere. URL→|static|
Directory→/home/username/project folder/static.
18 . In settings.py
STATIC_ROOT=BASE_DIR/’static’ Then command the static_DIR.code.
18. Go to bash console. Python manage.py collect static.
19. Go to web. reload→click link→Then RUN the project

You might also like