๐Ÿ Python Examples - Comprehensive Code Library
โ† Back to PranavKulkarni.org
Lesson 2 ยท Web Development

Django Framework & MVT Pattern

Develop large-scale, robust web applications with the feature-rich Django framework.

Batteries Included

Django is a "high-level Python web framework that encourages rapid development and clean, pragmatic design." It includes an ORM, auth system, admin interface, and more out of the box.

The MVT Pattern

  • Model: Defines the data structure (database abstraction).
  • View: Handles business logic and returns a response.
  • Template: Handles the presentation layer (HTML).

Creating a Model

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)

    def __str__(self):
        return self.title

Writing a View

from django.shortcuts import render
from .models import Post

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

The Admin Interface

Register your models to see them in the automatically generated admin site.

from django.contrib import admin
from .models import Post

admin.site.register(Post)

โœ… Practice (45 minutes)

  • Install Django: pip install django.
  • Start a new project: django-admin startproject myproject.
  • Create an app: python manage.py startapp blog.
  • Run migrations: python manage.py migrate.
  • Create a superuser: python manage.py createsuperuser.