Django

DONT FORGET TO REPLACE ME LATER

Django Overview

What is Django?

Django is a high-level Python web framework that enables rapid development of secure and maintainable websites. It follows the MTV (Model-Template-View) pattern (similar to MVC).

Key Features:

Philosophy:

“The web framework for perfectionists with deadlines”


Django vs Flask

FeatureDjangoFlask
TypeFull-stack frameworkMicro-framework
Philosophy“Batteries included”Minimalist, flexible
Learning CurveSteeperEasier to start
Admin PanelBuilt-inManual/third-party
ORMBuilt-in (Django ORM)Manual (SQLAlchemy)
AuthenticationBuilt-inManual/extensions
URL RoutingCentralizedDecorator-based
Project StructureOpinionatedFlexible
Best ForLarge, complex appsSmall to medium apps, APIs

Code Comparison

Flask (Minimal):

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

Django (Structured):

# views.py
from django.http import HttpResponse

def hello(request):
    return HttpResponse('Hello World!')

# urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.hello),
]

When to Use Each?

Choose Django if:

Choose Flask if:


Big Websites Using Django

๐ŸŒŸ Major Platforms:

  1. Instagram – Photo sharing (handles billions of requests)
  2. Spotify – Music streaming (backend APIs)
  3. YouTube – Video platform (some components)
  4. Dropbox – Cloud storage
  5. Pinterest – Image bookmarking
  6. NASA – Government websites
  7. The Washington Post – News media
  8. Mozilla – Firefox support sites
  9. Disqus – Comment hosting platform
  10. BitBucket – Code repository hosting

Why They Chose Django:


Django Project Structure

Based on your current file at blog:

Complete Structure:

blog/                              # PROJECT ROOT
โ”‚
โ”œโ”€โ”€ manage.py                      # CLI utility (you saw this earlier)
โ”‚
โ”œโ”€โ”€ blog/                          # PROJECT CONFIGURATION PACKAGE
โ”‚   โ”œโ”€โ”€ __init__.py               # Makes it a Python package
โ”‚   โ”œโ”€โ”€ settings.py               # โš™๏ธ Project settings
โ”‚   โ”œโ”€โ”€ urls.py                   # ๐Ÿ”— Main URL routing (you're viewing this)
โ”‚   โ”œโ”€โ”€ asgi.py                   # ASGI deployment config
โ”‚   โ””โ”€โ”€ wsgi.py                   # WSGI deployment config
โ”‚
โ”œโ”€โ”€ <app_name>/                    # DJANGO APP (e.g., posts, comments)
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ admin.py                  # Admin interface registration
โ”‚   โ”œโ”€โ”€ apps.py                   # App configuration
โ”‚   โ”œโ”€โ”€ models.py                 # ๐Ÿ“Š Database models
โ”‚   โ”œโ”€โ”€ views.py                  # ๐ŸŽฏ Business logic
โ”‚   โ”œโ”€โ”€ urls.py                   # App-specific URL routing
โ”‚   โ”œโ”€โ”€ tests.py                  # Unit tests
โ”‚   โ”œโ”€โ”€ forms.py                  # Form definitions (optional)
โ”‚   โ”‚
โ”‚   โ”œโ”€โ”€ migrations/               # Database migrations
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ””โ”€โ”€ 0001_initial.py
โ”‚   โ”‚
โ”‚   โ”œโ”€โ”€ templates/                # HTML templates
โ”‚   โ”‚   โ””โ”€โ”€ <app_name>/
โ”‚   โ”‚       โ””โ”€โ”€ template.html
โ”‚   โ”‚
โ”‚   โ””โ”€โ”€ static/                   # CSS, JS, images
โ”‚       โ””โ”€โ”€ <app_name>/
โ”‚           โ”œโ”€โ”€ css/
โ”‚           โ”œโ”€โ”€ js/
โ”‚           โ””โ”€โ”€ images/
โ”‚
โ”œโ”€โ”€ templates/                     # PROJECT-LEVEL TEMPLATES (optional)
โ”‚   โ””โ”€โ”€ base.html
โ”‚
โ”œโ”€โ”€ static/                        # PROJECT-LEVEL STATIC FILES (optional)
โ”‚   โ”œโ”€โ”€ css/
โ”‚   โ”œโ”€โ”€ js/
โ”‚   โ””โ”€โ”€ images/
โ”‚
โ”œโ”€โ”€ media/                         # USER-UPLOADED FILES
โ”‚   โ””โ”€โ”€ uploads/
โ”‚
โ”œโ”€โ”€ db.sqlite3                     # SQLite database (development)
โ”œโ”€โ”€ requirements.txt               # Python dependencies
โ”œโ”€โ”€ .env                          # Environment variables (not in git)
โ””โ”€โ”€ .gitignore                    # Git ignore file

Key Files Explained:

manage.py

# Command-line utility
python manage.py runserver        # Start server
python manage.py makemigrations   # Create migrations
python manage.py migrate          # Apply migrations

blog/settings.py

# Project configuration
INSTALLED_APPS = [...]   # Registered apps
DATABASES = {...}        # Database config
TEMPLATES = [...]        # Template settings
STATIC_URL = '/static/'  # Static files

urls.py (Your current file)

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),           # Admin interface
    path('', include('posts.urls')),           # Include app URLs
    path('api/', include('api.urls')),         # API endpoints
]

MTV Pattern (Django’s MVC):

Request Flow:
Browser โ†’ URLs โ†’ Views โ†’ Models/Templates โ†’ Response

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  URLs   โ”‚ โ† urlpatterns in urls.py
โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”˜
     โ”‚
โ”Œโ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”
โ”‚  Views  โ”‚ โ† Functions/classes in views.py
โ””โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”˜
     โ”‚
     โ”œโ”€โ”€โ”€โ”€โ”€โ–บ Models (Database)
     โ”‚
     โ””โ”€โ”€โ”€โ”€โ”€โ–บ Templates (HTML)

Creating Your First Structure:

# 1. Create app
python manage.py startapp posts

# 2. Add to settings.py INSTALLED_APPS
# 'posts',

# 3. Create model in posts/models.py
# 4. Create views in posts/views.py
# 5. Create URLs in posts/urls.py
# 6. Include in main urls.py

Your Current File (urls.py) is the main URL router – it’s the entry point for all HTTP requests to your Django project. Right now it only has the admin route. You’ll add more routes as you create apps!


Django Apps Explained

What is a Django App?

A Django app is a self-contained module that performs a specific function in your Django project. Think of it as a building block or component of your website.

Key Concept:

Project vs App

blog/                          # PROJECT (your entire site)
โ”œโ”€โ”€ manage.py
โ”œโ”€โ”€ blog/                      # Project configuration folder
โ”‚   โ”œโ”€โ”€ settings.py
โ”‚   โ””โ”€โ”€ urls.py               # โ† You're viewing this file
โ”œโ”€โ”€ posts/                     # APP #1 (handles blog posts)
โ”‚   โ”œโ”€โ”€ models.py
โ”‚   โ”œโ”€โ”€ views.py
โ”‚   โ””โ”€โ”€ urls.py
โ”œโ”€โ”€ comments/                  # APP #2 (handles comments)
โ”‚   โ”œโ”€โ”€ models.py
โ”‚   โ”œโ”€โ”€ views.py
โ”‚   โ””โ”€โ”€ urls.py
โ””โ”€โ”€ users/                     # APP #3 (handles user profiles)
    โ”œโ”€โ”€ models.py
    โ”œโ”€โ”€ views.py
    โ””โ”€โ”€ urls.py

Why Use Apps?

  1. Modularity: Each feature is isolated and maintainable
  2. Reusability: Apps can be used in multiple projects
  3. Organization: Code is logically separated
  4. Team Collaboration: Different developers can work on different apps

Creating an App

# In your terminal at c:\Users\Adam.Huang\Downloads\DE\django\blog\
python manage.py startapp posts

This creates:

posts/
โ”œโ”€โ”€ __init__.py          # Makes it a Python package
โ”œโ”€โ”€ admin.py            # Register models for admin interface
โ”œโ”€โ”€ apps.py             # App configuration
โ”œโ”€โ”€ models.py           # Database models (tables)
โ”œโ”€โ”€ views.py            # View functions (business logic)
โ”œโ”€โ”€ tests.py            # Unit tests
โ””โ”€โ”€ migrations/         # Database migration files
    โ””โ”€โ”€ __init__.py

App Structure Example

1. models.py – Define Data Structure

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

2. views.py – Handle Requests

from django.shortcuts import render
from .models import Post

def post_list(request):
    posts = Post.objects.all()
    return render(request, 'posts/post_list.html', {'posts': posts})

3. urls.py – App URL Routing

from django.urls import path
from . import views

urlpatterns = [
    path('', views.post_list, name='post_list'),
]

Connecting Apps to Your Project

Step 1: Add to INSTALLED_APPS

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'posts',  # โ† Add your app here
]

Step 2: Include App URLs

from django.contrib import admin
from django.urls import path, include  # โ† Add include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('posts/', include('posts.urls')),  # โ† Include app URLs
]

Now URLs like http://127.0.0.1:8000/posts/ will route to your posts app!

Built-in Django Apps

Your project already has these apps (check settings.py):

Common App Examples

Best Practices

โœ… DO:

โŒ DON’T:


Next Steps: Create your first app with python manage.py startapp posts and start building your blog!