Creating & Registering Apps
A Django project is made up of multiple apps. Each app is a self-contained module that handles a specific feature — like a blog app, users app, or API app. Apps are reusable and can be plugged into different projects.
What is a Django App?
An app is a web application that does something — a blog, a poll system, a user profile feature. A project can contain multiple apps, and an app can be in multiple projects. Apps promote modularity and reusability. Each app has its own models, views, templates, URLs, and tests.
QuerySets are LAZY — no DB hit until evaluated.
App Structure
- Create app: python manage.py startapp blog
- models.py — Database models for this app
- views.py — View functions/classes for this app
- urls.py — URL patterns (you create this manually)
- admin.py — Admin panel registration
- apps.py — App configuration class
- tests.py — Unit tests for this app
- migrations/ — Database migration files
- Register app in settings.py INSTALLED_APPS to activate it
Creating an App
# Create a new app called 'blog'
# python manage.py startapp blog
# App structure:
# blog/
# __init__.py
# admin.py <- Register models for admin panel
# apps.py <- App configuration
# models.py <- Database models
# tests.py <- Unit tests
# views.py <- View functions/classes
# migrations/
# __init__.py
# IMPORTANT: Register the app in settings.py
# mysite/settings.py
# INSTALLED_APPS = [
# 'django.contrib.admin',
# 'django.contrib.auth',
# 'django.contrib.contenttypes',
# 'django.contrib.sessions',
# 'django.contrib.messages',
# 'django.contrib.staticfiles',
# 'blog', # Add your app here!
# ]Tip
Tip
Use {% load static %} at the top of templates. In production, use WhiteNoise or a CDN to serve static files efficiently.
Common Mistake
Warning
Hardcoding static file paths like '/static/css/style.css'. Always use {% static 'css/style.css' %} for portable paths.
Practice Task
Note
(1) Create a static/css/style.css file. (2) Link it in base.html using {% static %}. (3) Run collectstatic.
Quick Quiz
Key Takeaways
- A Django project is made up of multiple apps.
- Create app: python manage.py startapp blog
- models.py — Database models for this app
- views.py — View functions/classes for this app