Django Tutorial — Learn Django Framework from Scratch

Django Tutorial — Learn Django Framework from Scratch

Global 0411 October 2024 Blog, Software Engineering, Tutorials

Introduction to Django, environment setup, project structure, models and views, templates, and deployment basics. Django's high-level Python web framework promotes quick development through simple, pragmatic design.

Introduction to Django

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It follows the MVT (Model–View–Template) pattern and ships with an ORM, URL routing, templates, forms, authentication, and an auto-generated admin.

MVT Flow

  • HTTP request → URLConf (urls.py) → View
  • View ↔ Model (models.py) via ORM
  • View → Template (.html) → HTTP response

Setting Up Your Environment

  • Install Python 3.10+ from python.org
  • Create venv:python -m venv .venv
  • Activate (Windows):.venv\Scripts\activate
  • Activate (macOS/Linux):source .venv/bin/activate
  • Install Django:pip install django
  • Create project:django-admin startproject mysite .
  • Run server:python manage.py runserver

Project Structure

mysite/
├── manage.py
├── mysite/              # Django config package: settings.py / urls.py / wsgi.py / asgi.py
└── core/                # app package (run: python manage.py startapp core)
    ├── models.py        # DB schema & ORM models
    ├── views.py         # Request handlers / controller logic
    ├── urls.py          # (optional) app-level route map
    └── templates/       # HTML templates used by this app

Your First View & Template

Create an app and a simple view that renders a template.

# create an app
python manage.py startapp core

# core/views.py
from django.shortcuts import render

def home(request):
    return render(request, "home.html", {"name": "Django"})
# mysite/urls.py
from django.contrib import admin
from django.urls import path
from core.views import home

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", home, name="home"),
]