Django is a high-level Python web framework that follows the Model-View-Template (MVT) architectural pattern. It is designed to help developers build clean, secure and scalable web applications quickly.
How Django Works?
Django handles HTTP requests and responses using the following process:
Client Sends Request:
A user enters a URL in the browser and sends request (e.g., https://example.com/home).
Django URL Dispatcher:
Django’s URL dispatcher (urls.py) maps the request to the corresponding view function
Django URL dispatcher (urls.py) checks to find a matching URL pattern.
If a match is found, Django calls the corresponding view function.
View (function) Processes the Request
It processes the request
The view retrieves data from the model (database) if needed.
Processes the logic
It passes the data to a template (HTML page, JSON data, etc).
Template Rendering:
The template dynamically generates the HTML content.
If the response requires an HTML page, Django loads the Template (.html file) and injects dynamic data into it.
Response Sent to the User
The generated response (HTML, JSON, etc.) is sent back to the user’s browser.
Django Project Directory Structure
When you create a Django project using:
django-admin startproject myproject
A directory named myproject/ is created with the following structure:
myproject/
│── manage.py
│── templates (Django template files html files are stored in this directory)
│── db.sqlite3
│── myproject/ # Main project package
│ │── __init__.py
│ │── settings.py
│ │── urls.py
│ │── asgi.py
│ └── wsgi.py
└── app_name/ (Created when running `startapp`)
│── migrations/
│── __init__.py
│── admin.py
│── apps.py
│── models.py
│── tests.py
│── views.py
│── tests.py
│── templates/
│── static/
└── urls.py (Manually created for app-specific routes)
Explanation of Important Files
1. manage.py
- A command-line tool to run the Django project.
- Used for running the server, creating apps, applying migrations, managing users, etc.
- Example commands:
python manage.py runserver # Start the development server
python manage.py makemigrations # Create migration files
python manage.py migrate # Apply migrations to the database
python manage.py createsuperuser # Create an admin user
2. myproject/ (Main Project Folder)
a) __init__.py
- An empty file that tells Python to treat this directory as a package.
A module is simply a Python file (.py) that contains functions, classes, or variables. It allows code to be logically organized.
Create a file named math_utils.py:
# math_utils.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Using the Module in Another File
# main.py
import math_utils
print(math_utils.add(5, 3)) # Output: 8
print(math_utils.subtract(5, 3)) # Output: 2
You can also import specific functions:
from math_utils import add
print(add(10, 20))
A package is a directory that contains a collection of modules and a special file named __init__.py (can be empty). It allows you to organize related modules together.
my_package/
│
├── __init__.py
├── math_utils.py
└── string_utils.py
math_utils.py
def multiply(a, b):
return a * b
string_utils.py
def greet(name):
return f"Hello, {name}!"
Using the Package in a Script
# main.py
from my_package import math_utils, string_utils
print(math_utils.multiply(3, 4)) # Output: 12
print(string_utils.greet("Krishna")) # Output: Hello, Krishna!
b) settings.py
- Main configuration file for the Django project.
- Contains settings for:
- Database Configuration (DATABASES)
- Installed Apps (INSTALLED_APPS)
- Middleware (MIDDLEWARE)
- Templates Configuration (TEMPLATES)
- Static and Media Files (STATIC_URL, MEDIA_URL)
c) urls.py
- Defines URL routing patterns for the project.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('app1/', include('app1.urls')), # Include app1's URLs ]
d) asgi.py & wsgi.py
- wsgi.py: Entry point for WSGI applications. Used for deploying Django projects on production servers. (WSGI servers e.g., Gunicorn, uWSGI))
- asgi.py: Entry point for ASGI applications for async operations (WebSockets, real-time applications)..
3. db.sqlite3 (Database)
- Default SQLite database file.
- Can be changed to PostgreSQL, MySQL, or other databases in settings.py.
4. app1/ (Django App)
Each Django project can have multiple apps, each responsible for a specific functionality and an app has its own structure:
- migrations/ → Stores database migration files (generated by makemigrations)..
- models.py → Defines the database models (tables) using Django ORM
- views.py → Contains logic for handling user requests and handles the logic for rendering webpages.
- urls.py (manually created) → Defines URLs specific to the app.
- admin.py → Registers models for Django’s admin panel.
- apps.py → Defines configuration for the app.
- tests.py → Contains test cases for the app.
- templates/ (HTML Files) Stores HTML templates for rendering dynamic webpages.
- static/ (CSS, JS, Images) Stores static files like CSS, JavaScript, and images.
Creating a Simple Django App
Create a Django project:
django-admin startproject myshop
cd myshop
Create an app:
python manage.py startapp testapp
Define a model (models.py in myapp/)
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
published_date = models.DateField()
Create and apply migrations:
python manage.py makemigrations myapp
python manage.py migrate
Define a view (views.py in myapp/)
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, Django!")
Map URL to the view (urls.py in myapp/)
from django.urls import path
from .views import home
urlpatterns = [
path('', home),
]
Include app URLs in the main project (urls.py in myproject/)
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
Run the server:
python manage.py runserver
Visit http://127.0.0.1:8000/ in your browser to see “Hello, Django!”.
Summary
- Django is a powerful and structured framework that simplifies web development with its built-in functionalities
- Django follows the MVT (Model-View-Template) architecture.
- The project directory is neatly organized into::
- manage.py (Project management tool)
- settings.py (Configuration)
- urls.py (URL routing)
- models.py (Database models)
- views.py (Business logic)
- templates/ (HTML files)
- static/ (CSS, JS, images)
- A Django project can have multiple apps, each managing a specific functionality.
- The app-level directories (handling models, views, and templates). Understanding this structure helps in building and managing scalable Django applications efficiently.