Introduction to Django

What is Django? Install, first project, venv, settings, manage.py, urls. Deep dive into Model-View-Template

1

Python Basics

Before diving into Django, let's ensure you have a solid foundation in Python. Django is built on Python, so understanding Python fundamentals is crucial.

Basic Python Concepts

# Variables and Data Types
name = "Django Developer"
age = 25
is_learning = True
skills = ["Python", "Django", "HTML", "CSS"]

# Functions
def greet(name):
    return f"Hello, {name}! Welcome to Django!"

# Classes
class Developer:
    def __init__(self, name, skills):
        self.name = name
        self.skills = skills
    
    def add_skill(self, skill):
        self.skills.append(skill)
        return f"Added {skill} to skillset"

Key Python concepts you should be familiar with: variables, data types, functions, classes, lists, dictionaries, and basic control structures.

2

What is Django?

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It follows the Model-View-Template (MVT) architectural pattern.

Key Features of Django

  • Rapid Development: Django's philosophy is to do things quickly
  • Secure: Built-in security features protect against common vulnerabilities
  • Scalable: Can handle high-traffic websites and applications
  • Versatile: Can build any type of website
  • Batteries Included: Comes with many built-in features

Django was created by Adrian Holovaty and Simon Willison in 2003 and was released publicly in 2005. It's named after the jazz guitarist Django Reinhardt.

3

Installation & Virtual Environment

Setting up a proper development environment is crucial. We'll use virtual environments to isolate our Django projects.

Creating a Virtual Environment

# Create a new directory for your project
mkdir django-course
cd django-course

# Create a virtual environment
python -m venv venv

# Activate the virtual environment
# On Windows:
venv\Scripts\activate

# On macOS/Linux:
source venv/bin/activate

# Install Django
pip install django

# Verify installation
python -m django --version

Virtual environments are essential because they allow you to have different versions of Python packages for different projects without conflicts.

4

First Django Project

Let's create your first Django project and understand the basic structure.

Creating a Django Project

# Create a new Django project
django-admin startproject myproject
cd myproject

# The project structure will be:
myproject/
├── manage.py
└── myproject/
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    ├── asgi.py
    └── wsgi.py

The `django-admin startproject` command creates the basic structure for a Django project. Let's explore each file:

Project Files Explained

  • manage.py: Django's command-line utility for administrative tasks
  • settings.py: Contains all project settings and configuration
  • urls.py: URL declarations for the project
  • wsgi.py: WSGI application entry point
  • asgi.py: ASGI application entry point
5

Django Apps vs Projects

Understanding the difference between Django apps and projects is crucial for building well-organized applications.

Django Project

  • A collection of settings and apps that make up a web application
  • Contains the main configuration files (settings.py, urls.py, wsgi.py)
  • Can contain multiple apps
  • Represents the entire web application
  • Created using `django-admin startproject`

Django App

  • A Python package that implements a specific functionality
  • Can be reused across different projects
  • Contains models, views, templates, and other components
  • Represents a specific feature or component
  • Created using `python manage.py startapp`

Think of a project as a website, and apps as the different features or sections of that website. For example, a blog website might have apps for 'blog posts', 'comments', 'user authentication', etc.

6

Creating Django Apps

Apps are the building blocks of Django applications. Let's learn how to create and configure them.

Creating a Django App

# Create a new app
python manage.py startapp blog

# The app structure will be:
blog/
├── __init__.py
├── admin.py
├── apps.py
├── models.py
├── tests.py
├── urls.py (you'll create this)
├── views.py
└── migrations/
    └── __init__.py

After creating an app, you need to register it in your project's settings.py file:

Registering an App in settings.py

# 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 new app here
]

Apps should be focused on a specific functionality. Common app names include 'blog', 'users', 'products', 'orders', etc.

7

Django App File Structure

Each Django app has a specific file structure. Understanding these files is essential for building Django applications.

Core App Files

  • __init__.py: Makes the directory a Python package
  • admin.py: Django admin interface configuration
  • apps.py: App configuration and metadata
  • models.py: Database models and schema
  • tests.py: Unit tests for the app
  • views.py: View functions and classes
  • urls.py: URL patterns for the app (you create this)

admin.py - Admin Interface

# admin.py
from django.contrib import admin
from .models import Post, Comment

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = ['title', 'author', 'created_date']
    list_filter = ['created_date', 'author']
    search_fields = ['title', 'content']

@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
    list_display = ['post', 'author', 'created_date']
    list_filter = ['created_date', 'author']

apps.py - App Configuration

# apps.py
from django.apps import AppConfig

class BlogConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'blog'
    verbose_name = 'Blog'

models.py - Database Models

# models.py
from django.db import models
from django.contrib.auth.models import User

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    created_date = models.DateTimeField(auto_now_add=True)
    updated_date = models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return self.title
    
    class Meta:
        ordering = ['-created_date']

views.py - View Functions

# views.py
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from .models import Post

def post_list(request):
    posts = Post.objects.all()
    return render(request, 'blog/post_list.html', {'posts': posts})

def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    return render(request, 'blog/post_detail.html', {'post': post})

@login_required
def post_create(request):
    # Logic for creating a new post
    pass

urls.py - URL Patterns

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

app_name = 'blog'

urlpatterns = [
    path('', views.post_list, name='post_list'),
    path('<int:pk>/', views.post_detail, name='post_detail'),
    path('create/', views.post_create, name='post_create'),
]

You'll also need to create a templates directory in your app for HTML templates, and optionally a static directory for CSS, JavaScript, and images.

8

Understanding manage.py

The `manage.py` file is Django's command-line utility for administrative tasks. It's your primary tool for interacting with your Django project.

Common manage.py Commands

# Run the development server
python manage.py runserver

# Create database tables
python manage.py migrate

# Create a new app
python manage.py startapp myapp

# Create a superuser
python manage.py createsuperuser

# Collect static files
python manage.py collectstatic

# Shell for interactive Python
python manage.py shell

These commands are essential for Django development. You'll use them frequently throughout your Django journey.

9

Django Settings

The `settings.py` file contains all the configuration for your Django project. Understanding these settings is crucial for proper project setup.

Key Settings in settings.py

# settings.py

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'your-secret-key-here'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition
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',
    }
}

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

# Media files
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

These settings control everything from database configuration to static files handling. We'll explore more settings as we progress.

10

URL Configuration

URLs in Django are the entry points to your application. They map web addresses to Python functions (views).

Basic URL Configuration

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),  # Include app URLs
]

# myapp/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('about/', views.about, name='about'),
    path('contact/', views.contact, name='contact'),
]

URL patterns use regular expressions to match URLs and route them to the appropriate view functions.

11

Deep Dive into Model-View-Template (MVT)

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

MVT Components

  • Model: Represents the data structure and database schema
  • View: Contains the business logic and handles requests
  • Template: Handles the presentation layer and user interface

Model Example

# models.py
from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    author = models.CharField(max_length=100)
    published_date = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return self.title
    
    class Meta:
        ordering = ['-published_date']

View Example

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

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

def article_detail(request, article_id):
    article = Article.objects.get(id=article_id)
    return render(request, 'article_detail.html', {'article': article})

Template Example

<!-- templates/home.html -->
<!DOCTYPE html>
<html>
<head>
    <title>My Django Blog</title>
</head>
<body>
    <h1>Welcome to My Blog</h1>
    {% for article in articles %}
        <article>
            <h2>{{ article.title }}</h2>
            <p>By {{ article.author }}</p>
            <p>{{ article.content|truncatewords:50 }}</p>
            <a href="{% url 'article_detail' article.id %}">Read more</a>
        </article>
    {% endfor %}
</body>
</html>

The MVT pattern promotes separation of concerns, making your code more maintainable and testable. Models handle data, Views handle logic, and Templates handle presentation.