Working and File Structure of Django

Let's imagine building a website like a simple online store using Django. Think of Django as a well-organized toolbox and a set of blueprints that help you build websites quickly and efficiently.
Django's Working in Simple Words: The MTV Pattern
Django uses a pattern called MTV (Model-Template-View), which is similar to MVC (Model-View-Controller) but with slightly different names. Think of it like this:
User Request (Browser): You type a website address (like www.mystore.com/products) in your browser and press Enter. This is the request.
URL Dispatcher (The Post Office): Django acts like a post office. It looks at the address you typed (/products) and figures out which "department" (Django calls them views) should handle this request. This is done by URL routing. Think of it as looking up the address in a directory to find the right department.
View (The Department): The "department" (view) is like the brains of the operation. It does the following:
Talks to the Model (The Data Storage): The view might need to get product information (like names, prices, descriptions) from the database. It uses Models to interact with the database easily. Models are like blueprints for how your data is organized (e.g., a "Product" model with fields for name, price, etc.).
Processes Data (Logic): The view might perform some logic, like filtering products, calculating discounts, or checking if you're logged in.
Prepares Data for the Template: The view gathers all the necessary data and sends it to the Template.
Template (The Presentation Layer): The Template is like a ready-made web page with placeholders. It's an HTML file with special Django tags. The view gives the template the data it prepared (like the list of products), and the template fills in the placeholders with this data to create the final HTML page that your browser can understand.
Response (Back to Browser): Django sends the generated HTML page back to your browser as a response. Your browser then displays the webpage showing the products.
In even simpler analogy:
Imagine ordering food at a restaurant:
User (You): You are the user making a request (ordering food).
URL Dispatcher (The Waiter): The waiter takes your order and directs it to the kitchen.
View (The Kitchen): The kitchen (view) gets your order, retrieves ingredients (data from the database via Models), cooks the food (processes data), and prepares it for serving (sends data to the template).
Template (The Plate and Presentation): The plate and how the food is arranged is like the template. It takes the cooked food (data) and presents it nicely.
Response (Served Food): The waiter serves you the food (the final webpage).
Django File Structure (Simplified Example)
When you start a Django project, it creates a basic file structure. Let's look at a simplified version for our online store example:
my_store_project/ (Your main project folder)
manage.py (A script to manage your Django project)
my_store_app/ (Your first Django app - e.g., for products)
__init__.py
models.py (Defines your data models - e.g., Product)
views.py (Handles logic and requests - e.g., showing product lists)
urls.py (Defines URLs specific to this app)
templates/ (Folder for HTML templates)
my_store_app/ (Recommended subfolder to avoid naming conflicts)
product_list.html (Template to display a list of products)
my_store_project/ (Project-level settings and URLs - same name as project folder)
__init__.py
settings.py (Project-wide settings - database, security, etc.)
urls.py (Project-level URL routing - connects app URLs)
asgi.py (For asynchronous server)
wsgi.py (For traditional web servers)
db.sqlite3 (Your default database file - for development)
content_copy download
Use code with caution.
Explanation of Key Files and Folders:
manage.py: A command-line utility that lets you run Django commands like starting the server, creating apps, running database migrations, etc.
my_store_app/: This is a Django app. Apps are like modules or components of your website. You can have multiple apps in a project (e.g., products, users, orders). Apps are designed to be reusable.
my_store_app/models.py: This file is where you define your Models. For example:
from django.db import models class Product(models.Model): name = models.CharField(max_length=100) description = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name
content_copy download
Use code with caution.Python
This code defines a Product model with fields for name, description, and price. Django uses this to create database tables and lets you interact with your data in Python.
my_store_app/views.py: This file contains your Views. For example:
from django.shortcuts import render from .models import Product def product_list(request): products = Product.objects.all() # Get all products from the database return render(request, 'my_store_app/product_list.html', {'products': products})
content_copy download
Use code with caution.Python
This product_list view fetches all Product objects from the database and passes them to the product_list.html template.
my_store_app/urls.py: This file defines the URLs for your app. For example:
from django.urls import path from . import views urlpatterns = [ path('products/', views.product_list, name='product_list'), ]
content_copy download
Use code with caution.Python
This code says that when someone goes to /products/ (within your app's URLs), Django should call the product_list view.
my_store_app/templates/my_store_app/product_list.html: This is an HTML Template. For example:
<!DOCTYPE html> <html> <head> <title>Product List</title> </head> <body> <h1>Our Products</h1> <ul> {% for product in products %} {# Django template tag to loop through products #} <li>{{ product.name }} - ${{ product.price }}</li> {# Access product attributes #} {% endfor %} </ul> </body> </html>
content_copy download
Use code with caution.Html
This template displays a list of products. {% for product in products %} and {{ product.name }} are Django template tags that allow you to use Python-like logic and display data passed from the view.
my_store_project/settings.py: This file holds settings for your entire Django project. Database configuration, installed apps, security settings, and much more are configured here.
my_store_project/urls.py: This is the project-level URL routing. It connects URLs from your apps to the main project. You would include your app's urls.py here.
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), # Django admin panel path('', include('my_store_app.urls')), # Include URLs from your app ]
content_copy download
Use code with caution.Python
This example includes the URLs defined in my_store_app/urls.py under the root path (''). So, /products/ will now be handled by my_store_app.urls.
In Summary:
Django provides a structured way to build websites using the MTV pattern. It separates concerns into Models (data), Views (logic), and Templates (presentation). The file structure helps organize your project into apps and manage settings and URLs. This structure makes it easier to build complex websites in a manageable and maintainable way.
Subscribe to my newsletter
Read articles from Singaraju Saiteja directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Singaraju Saiteja
Singaraju Saiteja
I am an aspiring mobile developer, with current skill being in flutter.