Django & Flask Topic

Django Introduction & Foundation: Project Setup, Apps, and MVT Pattern

What is Django?

Django is a high-level Python web framework that enables rapid development of secure and maintainable websites. Built by experienced developers, it handles much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel.

Key Django Philosophy:

  • "Batteries-included" - comes with most everything you need

  • Don't Repeat Yourself (DRY) principle

  • Clean, pragmatic design

Project Setup

Creating Your First Project

bash

# Create a new Django project
django-admin startproject myproject

# Navigate into your project directory
cd myproject

# View the project structure
ls
# You'll see:
# myproject/    (inner directory - your Python package)
# manage.py     (project management script)

Project Structure Explained

text

myproject/          # Outer directory - container for your project
├── manage.py       # Command-line utility for Django interactions
└── myproject/      # Inner directory - actual Python package
    ├── __init__.py
    ├── settings.py # Project configuration and settings
    ├── urls.py     # URL declarations - your "table of contents"
    ├── asgi.py     # ASGI config for async server deployment
    └── wsgi.py     # WSGI config for traditional server deployment

Understanding Django Apps

What are Apps?

In Django, a project is a collection of configuration and apps for a particular website. An app is a web application that does something specific (like a blog, forum, or poll system). A project can contain multiple apps.

Creating Your First App

bash

# Create a new app within your project
python manage.py startapp myapp

App Structure

text

myapp/
├── __init__.py
├── admin.py       # Register models for Django admin interface
├── apps.py        # App configuration
├── models.py      # Database models (M in MVT)
├── tests.py       # Test cases
├── views.py       # View functions/classes (V in MVT)
└── migrations/    # Database migration files
    └── __init__.py

The MVT (Model-View-Template) Pattern

Django follows the MVT pattern, which is a slight variation of the traditional MVC (Model-View-Controller) pattern.

1. Model (models.py)

  • Handles data and business logic

  • Defines your database structure

  • Each model maps to a database table

python

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

class Article(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    published_date = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return self.title

2. View (views.py)

  • Contains the business logic

  • Processes requests and returns responses

  • Acts as the bridge between models and templates

python

# myapp/views.py
from django.shortcuts import render
from .models import Article

def article_list(request):
    articles = Article.objects.all()
    return render(request, 'myapp/article_list.html', {'articles': articles})

3. Template (.html files)

  • Handles presentation layer

  • Defines how data is displayed

  • Uses Django Template Language (DTL)

html

<!-- myapp/templates/myapp/article_list.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Articles</title>
</head>
<body>
    <h1>All Articles</h1>
    {% for article in articles %}
        <div class="article">
            <h2>{{ article.title }}</h2>
            <p>{{ article.content }}</p>
            <small>Published: {{ article.published_date }}</small>
        </div>
    {% endfor %}
</body>
</html>

Key Configuration Files

settings.py - The Project's Heart

python

# myproject/settings.py

# Core settings
DEBUG = True  # Set to False in production!
ALLOWED_HOSTS = []  # Add your domain in production

# Installed apps - add your apps here
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',  # Your custom app
]

# Database configuration
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# URL for static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'

urls.py - The URL Dispatcher

python

# myproject/urls.py
from django.contrib import admin
from django.urls import path, include
from myapp import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('articles/', views.article_list, name='article_list'),
    # You can also include app-specific URLs
    path('myapp/', include('myapp.urls')),
]

# myapp/urls.py (create this file in your app)
from django.urls import path
from . import views

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

The Request-Response Flow

Understanding how a request flows through Django is crucial:

  1. URL Pattern Matching

    • User requests a URL (e.g., /articles/)

    • Django checks urls.py to find a matching pattern

    • Maps to the appropriate view function

  2. View Processing

    • View function receives the request object

    • Can interact with models to fetch/manipulate data

    • Processes business logic

  3. Template Rendering

    • View passes data to a template

    • Template renders the HTML with the provided data

    • Returns the final HTTP response

Practical Steps to Get Started

1. Create and Run Your Project

bash

# Create project
django-admin startproject mysite
cd mysite

# Create app
python manage.py startapp blog

# Run development server
python manage.py runserver

2. Register Your App

Add your app to INSTALLED_APPS in settings.py:

python

INSTALLED_APPS = [
    # ... default apps ...
    'blog',
]

3. Create Your First View

python

# blog/views.py
from django.http import HttpResponse

def home(request):
    return HttpResponse("Hello, Django! This is my first view.")

4. Configure URLs

python

# mysite/urls.py
from django.contrib import admin
from django.urls import path
from blog import views

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

5. Test Your Setup

bash

python manage.py runserver
# Visit http://127.0.0.1:8000 in your browser

This MVT foundation is what makes Django so powerful and organized. Every Django application you build will follow this same fundamental structure!

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?