Skip to content

1. Fundamentals

Getting Started

Django is a high-level Python web framework 🚀 that helps developers build secure, scalable, and maintainable web applications quickly. It follows the “batteries-included” philosophy, meaning it provides built-in features like authentication, ORM, admin panel, and security mechanisms.

Follows MVT (Model-View-Template) Architecture → A variation of MVC
Built-in ORM (Object-Relational Mapping) → Works with databases easily
Automatic Admin Interface → Manage your data without extra coding
Security Features → Protection against SQL injection, XSS, CSRF, etc.
Scalability & Performance → Used by large companies like Instagram & Pinterest
Flexible & Extensible → Supports APIs (Django REST Framework), caching, etc.

Django Architecture: MVT (Model-View-Template)

Section titled “Django Architecture: MVT (Model-View-Template)”

Django follows the MVT pattern, similar to MVC:

ComponentRole
ModelHandles database interactions (data storage & retrieval).
ViewProcesses requests, interacts with models, and returns responses.
TemplateManages presentation (HTML, CSS, etc.).

📌 In Django, the View acts as the Controller in MVC.

🔥 Instagram → Uses Django for handling millions of users
🔥 Pinterest → Django powers their image-heavy website
🔥 Spotify → Uses Django for backend services
🔥 NASA → Manages data with Django

✅ If you want to build web apps quickly
✅ If you need a secure, scalable backend
✅ If you prefer Python over JavaScript-heavy frameworks

Ensure you have Python installed (Django requires Python 3.6+).

  • Download and install Python from python.org.
  • Verify installation:
    Terminal window
    python --version
Section titled “2. Create a Virtual Environment (Recommended)”

To keep your projects isolated, create a virtual environment:

Terminal window
python -m venv myenv
source myenv/bin/activate # On macOS/Linux
myenv\Scripts\activate # On Windows

Use pip to install Django:

Terminal window
pip install django

Verify installation:

Terminal window
django-admin --version

Run the following command to start a new project:

Terminal window
django-admin startproject myproject
cd myproject

A Django project contains multiple apps and settings. Inside myproject/, you’ll see:

myproject/
│── manage.py
│── myproject/
├── __init__.py
├── settings.py
├── urls.py
├── asgi.py
├── wsgi.py
  • manage.py - Command-line utility for managing Django apps (modules).
  • settings.py - Configurations (database, installed apps, etc.).
  • urls.py - URL routing system.

Run the server to check if Django is working:

Terminal window
python manage.py runserver

Visit http://127.0.0.1:8000/ in your browser.

Django projects consist of multiple apps (modular components). To create an app:

Terminal window
python manage.py startapp myapp

This generates:

myapp/
├── migrations/
├── __init__.py
├── admin.py
├── apps.py
├── models.py
├── tests.py
├── views.py
  • models.py - Defines the database structure.
  • views.py - Handles logic and returns responses.
  • admin.py - Configures Django Admin.

Register your app in settings.py under INSTALLED_APPS:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
...
'myapp', # Add your app here
]

1.4 Step 4: Create a Model (Database Table)

Section titled “1.4 Step 4: Create a Model (Database Table)”

Edit models.py inside myapp/:

from django.db import models
class Item(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name

Run migrations to create the database:

Terminal window
python manage.py makemigrations
python manage.py migrate
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, Django!")

Edit myproject/urls.py:

from django.contrib import admin
from django.urls import path
from myapp.views import home
urlpatterns = [
path('admin/', admin.site.urls),
path('', home), # Homepage route
]

Restart the server and visit http://127.0.0.1:8000/.

Instead of returning plain text, use templates for HTML.

Inside myapp/, create a folder:

myapp/templates/

Create home.html inside it:

<!DOCTYPE html>
<html>
<head>
<title>My Django App</title>
</head>
<body>
<h1>Welcome to Django!</h1>
</body>
</html>

Edit views.py:

from django.shortcuts import render
def home(request):
return render(request, 'home.html')

Now, visit http://127.0.0.1:8000/ and see the HTML page.

Django has a built-in admin interface. First, create a superuser:

Terminal window
python manage.py createsuperuser

Then, start the server and visit: http://127.0.0.1:8000/admin/

  • Learn Django Forms, Models, and Views.
  • Work with Django ORM (database queries).
  • Use Django REST Framework for APIs.
  • Deploy Django using services like Heroku or DigitalOcean.

In Django, the terms project and web app refer to different components of a Django-based web development structure. Here’s the distinction between them:

  • A project in Django refers to the overall configuration and structure that holds one or more web applications.
  • It is essentially the container for your entire Django system. It includes settings, configurations, URLs, and other configurations that apply to the whole system.
  • A project is typically created with the django-admin startproject command, which sets up the basic directory structure for a Django application.
  • A Django project contains multiple apps that serve different functionalities.

Key points about a Django Project:

  • It defines the overall settings (e.g., database configuration, static files, middleware).
  • It holds the settings.py, urls.py, wsgi.py, and other configuration files.
  • It can consist of one or more Django apps.
  • The project’s urls.py file manages the routing of requests to the appropriate apps.

Example Structure:

my_project/
manage.py
my_project/
__init__.py
settings.py
urls.py
wsgi.py
  • A web app (or simply app) is a component within a Django project that provides a specific functionality or service.
  • Each web app is typically focused on a specific feature or functionality (e.g., a blog, an authentication system, a forum).
  • A Django app is created with the python manage.py startapp app_name command.
  • A Django app includes models, views, templates, URLs, and static files related to that specific functionality.

Key points about a Django Web App:

  • Each app is a modular component, typically focused on one piece of functionality.
  • A project can contain multiple apps that work together, with each app providing a different feature or service.
  • An app can be reused across multiple Django projects.

Example Structure of an App:

my_app/
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
migrations/
FeatureDjango ProjectDjango Web App
ScopeThe overall configuration and structure.A modular unit with specific functionality.
PurposeHouses one or more apps and the project settings.Provides a specific feature (e.g., blog, user authentication).
Creation Commanddjango-admin startproject <project_name>python manage.py startapp <app_name>
StructureIncludes settings, URLs, and configurations.Includes models, views, templates, static files.
ReusabilityNot typically reused across projects.Can be reused across multiple projects.

In Django, when registering an app in the INSTALLED_APPS list in settings.py, you can provide the full app name, which is typically the Python path to the app. This is useful for applications that are in a subdirectory or for apps that are packaged as a module.

Here’s how to register an app with its full name in INSTALLED_APPS:

If your app is located in a subdirectory or in a specific module, you would use the full Python path to the app. For instance:

  1. For a local app (e.g., if your app is named myapp in the same directory as your project):

    INSTALLED_APPS = [
    'myapp', # Simple app registration (usually works if the app is in the same directory)
    ]
  2. For an app located in a subdirectory (e.g., if your app is in a subfolder called apps/myapp):

    INSTALLED_APPS = [
    'apps.myapp', # Full app name using a Python import path
    ]
  3. For a third-party app (e.g., if you’re using a third-party app called django_extensions):

    INSTALLED_APPS = [
    'django_extensions', # Third-party app using its full name
    ]
  4. For an app in a nested module (e.g., if the app is within a package structure like myproject.apps.myapp):

    INSTALLED_APPS = [
    'myproject.apps.myapp', # Full Python path to the app
    ]
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'apps.myapp', # Full app name with package path
'django_extensions', # Third-party app
]

In Django, if an app is not registered in the INSTALLED_APPS list in settings.py, several things can go wrong, and its functionality will be impacted. Here’s what will happen if an app is not registered:

If the app is not listed in INSTALLED_APPS, Django will not recognize the app’s models. This means:

  • Migration Files: Django won’t be able to detect the app’s migrations. Therefore, if you try to run python manage.py makemigrations or python manage.py migrate, Django won’t create or apply migrations for the unregistered app.
  • Database Tables: Since the app’s models are not loaded, Django will not create the corresponding database tables for the models of that app.
  • Querying Models: You won’t be able to query or interact with models from the unregistered app (i.e., you can’t create, retrieve, update, or delete objects for that app).

The Django admin interface will not show models from the unregistered app. This is because the admin interface dynamically loads models from the registered apps. Without registration in INSTALLED_APPS, Django won’t load the models and therefore won’t display them in the admin interface.

If your app defines any custom template tags or filters (in templatetags), they will not be available in your templates if the app is not registered in INSTALLED_APPS. Template tags and filters are loaded from installed apps, and Django needs to know about the app in INSTALLED_APPS to find and use them.

Django won’t know to include or serve any static files (CSS, JavaScript, images) or media files associated with the app if it’s not in INSTALLED_APPS. Specifically:

  • Static files: Django won’t include the app’s static files in the static directory and won’t be able to serve them using collectstatic.
  • Media files: Similarly, Django won’t know about media files if the app is unregistered, so any media file storage configurations related to that app may not work.

If the app contains any signals (such as post-save or pre-save signals), they won’t be registered or executed if the app is not included in INSTALLED_APPS. Django won’t load any signal handlers, so these won’t trigger in response to model changes or other events.

If your app defines views and URL patterns:

  • Views: If your app is not in INSTALLED_APPS, Django won’t know about the views within that app. Consequently, any URLs mapped to views in that app won’t work.
  • URLs: The app’s URL patterns won’t be included in your main project’s URL routing. So, any URL patterns defined in that app won’t be recognized by Django.

Other features that depend on INSTALLED_APPS, such as signals, middlewares, or even some third-party packages, will not function if the app is missing from the list.