Python Docs

Django

Django is a high-level, batteries-included Python web framework that helps you build secure and scalable web applications rapidly. It comes with an ORM, authentication system, template engine, admin panel, forms, and many more built-in features.

Why Django?

  • Fast development with built-in tools.
  • Secure by default (CSRF, XSS, SQL injection protections).
  • Scalable and used in production by large companies.
  • ORM to work with databases using Python classes.
  • Admin panel auto-generated from your models.

Install & Start a Project

Use django-admin to create a new project and manage.py to run commands inside it.

Example: Project and App Setup

pip install django
django-admin startproject mysite
cd mysite
python manage.py startapp blog
python manage.py runserver

Folder structure (simplified):

mysite/
  manage.py
  mysite/
    settings.py
    urls.py
    wsgi.py
  blog/
    models.py
    views.py
    urls.py
    templates/blog/

Model, Migration & Admin

Django’s ORM lets you define models as Python classes and automatically create database tables via migrations. The same models power the admin panel.

Defining a Model

# blog/models.py
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    created_at = models.DateTimeField(auto_now_add=True)
# mysite/settings.py → add app
INSTALLED_APPS += ['blog']

# Run migrations
python manage.py makemigrations
python manage.py migrate

# Create admin user
python manage.py createsuperuser

What this does:

  • Post model creates a blog_post table in the database.
  • auto_now_add=True stores timestamp when the post is created.
  • makemigrations generates migration files.
  • migrate applies them to the database.
  • createsuperuser sets up a user for Django admin.

View, URL & Template

Django follows the MVT pattern (Model–View–Template). A request goes through the URL, then hits a view function, which uses models and returns a rendered template.

View Function

# blog/views.py
from django.shortcuts import render
from .models import Post

def index(request):
    posts = Post.objects.order_by('-created_at')
    return render(request, 'blog/index.html', {'posts': posts})
# mysite/urls.py
from django.urls import path, include

urlpatterns = [
    path('', include('blog.urls')),
]
# blog/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]
<!-- blog/templates/blog/index.html -->
{% for p in posts %}
  <p>{{ p.title }}</p>
{% endfor %}

Flow:

Request  →  URL ('')  →  blog.urls  →  views.index  →  template (index.html)

Notes & Best Practices

  • Use Django admin for quick CRUD on your models.
  • For APIs, integrate Django REST Framework (DRF).
  • Split apps logically (users, blog, payments, etc.).
  • Use environment variables for secrets and database URLs.
  • Enable debug = False and proper allowed hosts in production.