Learn Django Β· 2/13

Django's Brain: Architecture & Apps 🧠

6 min read

Django's Brain: Architecture & Apps 🧠

Welcome to the internal wiring of Django.

If you’ve just installed Django, you probably saw a bunch of files auto-generate. It looks intimidating. It looks like someone spilled a dictionary into your hard drive. Don't panic. 😌

In this section, we are going to dissect how Django "thinks," how to organize your code so you don't hate yourself three months from now, and how to create your first module.


1. The MVT (Model-View-Template) Pattern Explained

Before we write code, we must understand the blueprint.

The Problem

Imagine you are building a website without a structure. You write SQL queries inside your HTML files. You write Python logic inside your database scripts. You change the font color, and suddenly the database stops working. This is called "Spaghetti Code." It is delicious on a plate but a disaster in software.

The Solution: Separation of Concerns

Django solves this by splitting responsibilities into three distinct layers. This is known as the MVT architecture.

You might hear about MVC (Model-View-Controller) in other frameworks. Django is essentially MVC, but the naming convention is slightly different.

  1. Model (The Data Layer): This handles the database. It describes what your data looks like. You define a Python class, and Django builds the SQL table for you.
  2. View (The Logic Layer): This is the brain. It receives a request, checks the Model for data, applies logic (filtering, calculations), and decides which Template to show.
  3. Template (The Presentation Layer): This is what the user sees. It is HTML mixed with Django Template Language (DTL) to display dynamic data.

πŸ” Deep Dive: The Flow

Let's look at this practically.

Scenario: You are running a high-end Pizza Shop.
The Goal: A customer wants to order a Pepperoni Pizza.

  1. The URL (The Receptionist): The customer walks in and says "I want pizza" (Accesses /menu/pizza/). The URL dispatcher points them to the correct waiter.
  2. The View (The Waiter): The View receives the order. It knows it cannot make the pizza itself. It needs ingredients.
  3. The Model (The Pantry/Kitchen): The View asks the Model, "Do we have Pepperoni?" The Model queries the database and returns the data object: Pizza: Pepperoni.
  4. The Template (The Plating): The View takes the data (the pizza) and hands it to the Template. The Template arranges it nicely on a plate (HTML/CSS) so it looks tasty.
  5. Response: The customer receives the HTML page.

Industry Note: In Django, the "Controller" part of MVC is actually handled by the Django framework itself (the URL routing and request handling). That is why we call it MVT.


2. Projects vs. Apps: Modularizing Your Code

This is the number one confusion point for beginners.

The Problem

If you put all your code (User authentication, Blog posts, Payment processing, Chat system) into one giant folder, your code becomes a "Monolith." If the Chat system breaks, it might take down the Payments too.

The Solution: Modularization

Django distinguishes between a Project and an App.

  • The Project: The configuration container. It contains settings, generic assets, and the main URL routing. It’s the whole website (e.g., "Facebook").
  • The App: A Python package that does one specific thing. It contains Models, Views, and URLs for that feature (e.g., "Messenger", "Groups", "Marketplace").

πŸ—οΈ Architecture Visualization

Think of your Django Project as a Smartphone.
Think of Django Apps as the Applications installed on that phone.

  • Project: my_website (Contains settings.py, manages the database connection).
  • App 1: authentication (Handles login/logout).
  • App 2: blog (Handles posts, comments).
  • App 3: store (Handles products, cart).

Fact: A well-written Django App can be unplugged from one project and plugged into another with minimal changes. This is called "Reusability." Many industry plugins (like django-allauth for login) are just apps you install.


3. Creating Your First App

Let's get our hands dirty. We will create an app to manage a simple blog.

Step 1: Terminal Command

Make sure you are in the same folder as manage.py.

bash
python manage.py startapp blog
  • python manage.py: This is your command stick.
  • startapp: The command to generate the app structure.
  • blog: The name of your app.

Step 2: The Folder Structure

Django just created a folder named blog. Let's look inside:

text
blog/
    β”œβ”€β”€ __init__.py      # Tells Python this is a package
    β”œβ”€β”€ admin.py         # Configuration for the built-in Admin panel
    β”œβ”€β”€ apps.py          # App metadata (don't touch this yet)
    β”œβ”€β”€ migrations/      # Stores changes to your database structure (HISTORY of your DB)
    β”œβ”€β”€ models.py        # ⚠️ CRITICAL: Your database tables go here
    β”œβ”€β”€ tests.py         # Where you write tests (Please write tests)
    └── views.py         # ⚠️ CRITICAL: Your logic goes here
  • models.py: You will spend 40% of your time here defining data structures.
  • views.py: You will spend 40% of your time here writing logic.
  • urls.py: Wait! It's missing. By default, apps don't create their own urls.py. Industry standard is to manually create a urls.py inside the app folder to keep routing isolated.

4. Registering Apps and Navigating settings.py

You created the app. You wrote code. You ran the server. Nothing happened.
Why? Because Django is like a strict bouncer. If you aren't on the list, you don't get in.

The Problem

Django doesn't automatically scan every folder to see if it's an app. This saves memory and prevents conflicts. You must explicitly tell the Project that the App exists.

The Solution: INSTALLED_APPS

Open the settings.py file in your Project folder (not the app folder).

Look for the list called INSTALLED_APPS. It probably looks like this:

python
# settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Your apps go here:
    'blog', 
]

πŸ› οΈ Industry Best Practices for settings.py

The settings.py file is the control center. Here are the knobs you need to know immediately:

  1. INSTALLED_APPS:

    • Add your new app name (e.g., 'blog') here immediately after creating it.
    • Funny Note: Forgetting this step is the "I plugged in the toaster but didn't turn on the socket" of Django development. You will do it at least once.
  2. DEBUG:

    • Development: True. Shows detailed error pages (the yellow screen of death) that help you debug.
    • Production: False. Never leave this True in production. If you do, hackers can see your server variables, code snippets, and database structure.
  3. ALLOWED_HOSTS:

    • A security measure. Who is allowed to serve this site?
    • Local: ['localhost', '127.0.0.1']
    • Production: ['www.myawesomesite.com']
  4. SECRET_KEY:

    • It signs session cookies and manages cryptographic signing.
    • Rule: Keep it secret. Keep it safe. If someone steals this, they can hijack user sessions. Do not commit this to GitHub in a real project (use Environment Variables instead).

Summary Checklist

  1. Architecture: MVT (Model = Data, View = Brains, Template = Face).
  2. Structure: Project = House; App = Room.
  3. Action: Run python manage.py startapp <appname>.
  4. Config: Add '<appname>' to INSTALLED_APPS in settings.py.

Now that the brain is wired up, we are ready to define some data models in the next chapter.


πŸ“š References & Further Reading

Challenge

You are a developer working on a Django project named e_commerce_project. Your task is to integrate a new app called inventory.

Your goal is to write the Python code for the necessary files to define a product model, create a view to display all products, configure the app-specific URLs, and correctly register the app within the project settings.

Your Tasks:

  1. In inventory/models.py:

    • Define a model class named Product.
    • It should have three fields:
      • name: A character field with a maximum length of 200.
      • sku: A unique character field (Stock Keeping Unit) with a maximum length of 50.
      • is_active: A boolean field that defaults to True.
  2. In inventory/views.py:

    • Create a function-based view named all_products that takes a request object.
    • This view should query the database for all Product objects.
    • It should then render a template located at inventory/product_list.html, passing the queried products to the template's context with the key 'products'.
  3. In inventory/urls.py:

    • Create the URL configuration for the inventory app.
    • Define a single URL pattern that maps the app's root path ('') to the all_products view you created. Give this URL pattern the name product-list.
  4. In e_commerce_project/settings.py:

    • Register the new inventory app in the INSTALLED_APPS list.
    • For production readiness, set the DEBUG setting to False.
    • Update ALLOWED_HOSTS to permit traffic from the domain "www.example.com".

Expected result

Your final code should correctly implement the requested features in the four specified file sections. The LLM will evaluate your submission based on the following criteria:

e_commerce_project/settings.py

python
# ...
DEBUG = False
ALLOWED_HOSTS = ['www.example.com']
INSTALLED_APPS = [
    # ... default apps
    'inventory',
]
# ...
  • The inventory app must be added as a string to the INSTALLED_APPS list.
  • The DEBUG variable must be set to False.
  • The ALLOWED_HOSTS list must contain the string 'www.example.com'.

inventory/models.py

python
from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=200)
    sku = models.CharField(max_length=50, unique=True)
    is_active = models.BooleanField(default=True)
  • Imports models from django.db.
  • Defines a class Product that inherits from models.Model.
  • Contains a CharField named name with max_length=200.
  • Contains a CharField named sku with max_length=50 and unique=True.
  • Contains a BooleanField named is_active with default=True.

inventory/views.py

python
from django.shortcuts import render
from .models import Product

def all_products(request):
    products = Product.objects.all()
    context = {'products': products}
    return render(request, 'inventory/product_list.html', context)
  • Imports render from django.shortcuts and the Product model.
  • Defines a function all_products that accepts request.
  • Correctly queries all objects from the Product model.
  • Calls render with the request, the correct template path, and a context dictionary containing the products.

inventory/urls.py

python
from django.urls import path
from . import views

urlpatterns = [
    path('', views.all_products, name='product-list'),
]
  • Imports path from django.urls and views from the current app.
  • Defines a list named urlpatterns.
  • Includes a path object that maps the empty string '' to views.all_products and assigns the name product-list.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.