-
Django is an open-source web development framework written in Python.
-
Django provides features such as
Templates
,Libraries
, andAPIs
. -
Django is popular because of its ease of scalability.
-
Django is a
Full-Stack
framework, but developers can use it to createbackend
systems and connect them with any frontend framework likeReact
,Angular
,Vue
, etc., throughAPI
.
- Python Interpreter: First, you need a Python interpreter. Select it from the
Command Palette
in VSCode.
-
Create a Virtual Environment:
- Use the following command:
python -m venv .venv
.venv
is the folder name where the virtual environment is created. You can name this folder anything you like.- Python recommends using a virtual environment to build Python applications.
- A
Virtual Environment
is an isolated environment that has its own copy of the interpreter and libraries to avoid conflicts with the global Python installation.
- Use the following command:
-
Activate the Virtual Environment:
- Use the following command:
.venv\Scripts\activate
- Use the following command:
-
Install the Django Framework:
- Use the following command:
pip install Django
- To deactivate the virtual environment, simply use:
deactivate
- Use the following command:
-
In Django, a
Project
represents an entire web application. -
An
App
is a sub-module of a project. -
A
Project
can have multipleApps
. -
A Django
Project
is a Python package that includes the configuration for the database, various sub-modules known asApps
, and other settings specific to Django.
First, ensure you have Django installed. You can install it using pip
:
pip install django
To create a new Django project, use the django-admin
command followed by startproject
and your project name. For example, to create a project named myproject
:
django-admin startproject myproject
This will create a directory structure like this:
myproject/
manage.py
myproject/
__init__.py
settings.py
urls.py
wsgi.py
asgi.py
Change into the project directory:
cd myproject
Inside your project directory, create a new Django app using the manage.py
script. For example, to create an app named myapp
:
python manage.py startapp myapp
This will create a directory structure like this:
myapp/
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
migrations/
__init__.py
To make Django recognize the app, you need to add it to the INSTALLED_APPS
list in your project's settings.py
file.
Open myproject/settings.py
and add 'myapp',
to the INSTALLED_APPS
list:
INSTALLED_APPS = [
...
'myapp',
]
Django manages the databases operations with the ORM techniques. ORM, or Object-Relational Mapping, is a programming technique used to interact with a database using an object-oriented paradigm. In the context of Django, ORM allows developers to work with databases using Python classes and objects rather than writing raw SQL queries.
-
Definition:
- Object-Relational Mapping (ORM) is a method of mapping a database schema to an object-oriented model. It allows developers to manipulate database entries as if they were regular Python objects.
-
How ORM Works in Django:
- Django ORM translates Python code into SQL queries. It provides a high-level abstraction over the database that lets you interact with it using Python instead of SQL.
- You define your database schema as Python classes (called models), and Django handles the SQL behind the scenes to create and manage the database tables.
-
Advantages of Using ORM:
- Simplicity: ORM abstracts the database operations, making it easier for developers to interact with the database.
- Portability: The same ORM code can work with different databases (e.g., SQLite, PostgreSQL, MySQL) without modification.
- Security: ORM helps prevent SQL injection attacks by using parameterized queries.
In Django, you define your database schema using models. Here is an example of a simple model representing a Book
:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
published_date = models.DateField()
def __str__(self):
return self.title
After defining your models, you need to create and apply migrations to generate the corresponding database tables. This is how Django manages the database schema.
-
Create Migrations:
python manage.py makemigrations
-
Apply Migrations:
python manage.py migrate
The above two commands should be run whenever a new model is created or any change is done in existing model.
Once the migrations are applied, you can use the ORM to create, retrieve, update, and delete records in the database.
-
Open the Django Shell
python manage.py shell
-
Create a Record:
from myapp.models import Book book = Book(title="Django for Beginners", author="John Doe", published_date="2023-01-01") book.save()
-
Retrieve Records:
all_books = Book.objects.all() book = Book.objects.get(id=1)
-
Update a Record:
book = Book.objects.get(id=1) book.title = "Advanced Django" book.save()
-
Delete a Record:
book = Book.objects.get(id=1) book.delete()
-
Exit from the shell
exit()
Define a simple view in myapp/views.py
. For example:
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, world! This is my home page.")
Create a URL configuration for your app. In myapp
, create a file named urls.py
and add:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
Then, include this URL configuration in your project’s urls.py
file (myproject/urls.py
):
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
Start the development server to see your project in action:
python manage.py runserver
Open a web browser and go to http://127.0.0.1:8000/
. You should see the message "Hello, world! This is my home page."
The MVT (Model-View-Template) architecture is the design pattern used by Django to build web applications. It is a variation of the MVC (Model-View-Controller) pattern tailored to suit the needs of web development with Django. Here’s an overview of each component in the MVT architecture:
-
Model:
- The Model is the data access layer. It defines the structure of the database, including the tables and their relationships, as well as the methods to interact with the data.
- In Django, models are defined as Python classes, which Django's ORM (Object-Relational Mapping) then translates into database tables.
- Example:
from django.db import models class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=100) published_date = models.DateField()
-
View:
- The View is the business logic layer. It processes user requests, interacts with the model to retrieve data, and determines what data to send back to the user.
- Views in Django are Python functions or classes that receive web requests and return web responses.
- Example:
from django.shortcuts import render from .models import Book def book(request): books = Book.objects.all() return render(request, 'book.html', {'books': books})
-
Template:
- The Template is the presentation layer. It defines how the data received from the view should be displayed to the user.
- Templates in Django are HTML files with Django Template Language (DTL) which allows for dynamic content insertion.
- Example (
home.html
):<!DOCTYPE html> <html> <head> <title>Home Page</title> </head> <body> <h1>Book List</h1> <ul> {% for book in books %} <li>{{ book.title }} by {{ book.author }}</li> {% endfor %} </ul> </body> </html>
-
Request:
- A user sends a request to the Django application by entering a URL in the browser.
-
URL Routing:
- Django uses URLconf to map the URL to a specific view. The
urls.py
file contains these mappings. - Example (
urls.py
):from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ]
- Django uses URLconf to map the URL to a specific view. The
-
View Processing:
- The view function associated with the URL is called. This view processes the request, interacts with the model to get data, and passes the data to the template.
- Example view (
views.py
):def home(request): books = Book.objects.all() return render(request, 'home.html', {'books': books})
-
Template Rendering:
- The template receives the data from the view and renders it into HTML to be sent back to the user.
- Example template (
home.html
):<ul> {% for book in books %} <li>{{ book.title }} by {{ book.author }}</li> {% endfor %} </ul>
-
Response:
- The rendered HTML is sent back to the user’s browser as a response, which displays the data in a web page.
The MVT architecture in Django allows for a clear separation of concerns:
- Model: Manages the data and database interactions.
- View: Contains the business logic and handles user requests.
- Template: Defines the presentation and how data is displayed to the user.
This structure helps in organizing code, making it more maintainable and scalable.