← Back to Module

Django Basics

CMM721: Web Application Development - Session 6

Birmingham Newman University

Lecturer: James Williams

Masters Level Conversion Course

3-hour session • 18 slides • 2 tasks • Django diagrams

Session Timeline:

  • 10 min: Registration & waiting
  • 20 min: Opening slides
  • 45 min: Task 1
  • 15 min: Break/Catch up
  • 20 min: Secondary slides
  • 45 min: Task 2
  • Remaining: Self-study

Learning Objectives

  • Understand Django framework architecture
  • Create Django projects and applications
  • Implement URL routing and views
  • Work with Django templates
  • Handle static files
  • Configure Django settings

What is Django?

Django: High-level Python web framework
  • Philosophy: "Batteries included" - everything you need
  • Pattern: MTV (Model-Template-View) similar to MVC
  • Features: ORM, admin interface, authentication, security
  • Used by: Instagram, Pinterest, NASA, Spotify

Why Django?

  • Rapid development
  • Security built-in (CSRF, XSS, SQL injection protection)
  • Scalable architecture
  • Excellent documentation

Django MTV Architecture

HTTP Request → URL Pattern
View (Business Logic)
Model (Database)
Template (HTML)
HTTP Response
  • Model: Data structure and database logic
  • Template: Presentation layer (HTML)
  • View: Business logic and request handling

Installation

Setting Up Django:

# Create virtual environment
python -m venv venv

# Activate (Windows)
venv\Scripts\activate

# Activate (Mac/Linux)
source venv/bin/activate

# Install Django
pip install django

# Verify installation
python -m django --version

Creating a Django Project

# Create project
django-admin startproject myproject

# Project structure:
myproject/
  manage.py
  myproject/
    __init__.py
    settings.py
    urls.py
    asgi.py
    wsgi.py

# Run development server
python manage.py runserver

# Visit: http://127.0.0.1:8000/

🎯 Project Structure Visualization

Django Project Layout

📁 myproject/ (root directory)
📄 manage.py - Command-line utility
📁 myproject/ (project package)
📄 settings.py - Configuration
📄 urls.py - URL routing
📄 wsgi.py - Deployment
📄 asgi.py - Async deployment
📁 myapp/ (application)
📄 models.py - Data models
📄 views.py - Views/Logic
📄 urls.py - App URLs
📄 admin.py - Admin config
📄 tests.py - Unit tests
📁 templates/ - HTML files
📁 static/ - CSS, JS, images

Creating an App

# Create app
python manage.py startapp blog

# Register app in settings.py
INSTALLED_APPS = [
  'django.contrib.admin',
  'django.contrib.auth',
  # ...
  'blog', # Add your app
]
Project vs App:
- Project: Entire website/application
- App: Module with specific functionality (blog, shop, etc.)

Views and URLs

Create a View (views.py):

from django.http import HttpResponse
from django.shortcuts import render

def home(request):
  return HttpResponse("<h1>Welcome to CMM721!</h1>")

def about(request):
  context = {'course': 'CMM721'}
  return render(request, 'about.html', context)

URL Configuration (urls.py):

from django.urls import path
from . import views

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

🎯 URL Routing Flow Diagram

Request to Response Flow

1. Browser Request: http://localhost:8000/blog/
2. Django URLconf: Match URL pattern in urls.py
3. View Function: Execute views.blog_list()
4. Query Database: Get blog posts from models
5. Render Template: blog_list.html with data
6. HTTP Response: HTML sent to browser

Task 1: Build First Django App

Objective:

Create a personal portfolio website using Django

Requirements:

  1. Create Django project: portfolio_project
  2. Create app: portfolio
  3. Create 3 views: home, about, contact
  4. Set up URL patterns for each view
  5. Create basic HTML responses (no templates yet)
  6. Test all URLs in browser

Deliverables:

  • Working Django project
  • Screenshot of each page
  • urls.py and views.py files

Django Templates

Template Basics:

<!-- templates/home.html -->
<!DOCTYPE html>
<html>
<head>
  <title>{{ title }}</title>
</head>
<body>
  <h1>Welcome {{ user.username }}!</h1>
  <p>{{ content }}</p>
  
  {% for item in items %}
    <div>{{ item.name }}</div>
  {% endfor %}
</body>
</html>

Template Syntax

Variables:

{{ variable }}
{{ user.name }}
{{ items.0.title }}

Tags:

{% if user.is_authenticated %}
  Welcome {{ user.username }}!
{% else %}
  Please log in.
{% endif %}

{% for post in posts %}
  <h2>{{ post.title }}</h2>
{% empty %}
  <p>No posts yet.</p>
{% endfor %}

Filters:

{{ text|lower }}
{{ date|date:"Y-m-d" }}
{{ content|truncatewords:30 }}

Template Inheritance

Base Template (base.html):

<!DOCTYPE html>
<html>
<head>
  <title>{% block title %}CMM721{% endblock %}</title>
</head>
<body>
  <nav>Navigation here</nav>
  {% block content %}{% endblock %}
  <footer>Footer here</footer>
</body>
</html>

Child Template (home.html):

{% extends 'base.html' %}

{% block title %}Home - CMM721{% endblock %}

{% block content %}
  <h1>Welcome Home</h1>
  <p>Page content here</p>
{% endblock %}

Static Files

Configuration (settings.py):

STATIC_URL = '/static/'
STATICFILES_DIRS = [
  BASE_DIR / 'static',
]

Using Static Files in Templates:

{% load static %}

<link rel="stylesheet" href="{% static 'css/style.css' %}">
<img src="{% static 'images/logo.png' %}">
<script src="{% static 'js/script.js' %}"></script>

Folder Structure:

static/
  css/
    style.css
  js/
    script.js
  images/
    logo.png

Task 2: Build Template System

Objective:

Enhance portfolio with Django templates and static files

Requirements:

  1. Create base.html with navigation and footer
  2. Create child templates extending base (home, about, contact)
  3. Add static CSS file with custom styling
  4. Add static JavaScript for interactive elements
  5. Include logo/images in static files
  6. Implement template inheritance properly
  7. Pass context data from views to templates

Bonus:

  • Add a projects list page with loop
  • Implement conditionals in templates
  • Add template filters for formatting

Django Settings

Important Settings:

# settings.py

SECRET_KEY = 'your-secret-key'
DEBUG = True # Set False in production

ALLOWED_HOSTS = ['localhost', '127.0.0.1']

INSTALLED_APPS = [...]

DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': BASE_DIR / 'db.sqlite3',
  }
}

TIME_ZONE = 'Europe/London'
LANGUAGE_CODE = 'en-gb'

Django Management Commands

# Run development server
python manage.py runserver

# Create database migrations
python manage.py makemigrations
python manage.py migrate

# Create superuser
python manage.py createsuperuser

# Start new app
python manage.py startapp myapp

# Run tests
python manage.py test

# Collect static files
python manage.py collectstatic

# Open Django shell
python manage.py shell

Best Practices

  • Virtual Environment: Always use venv
  • SECRET_KEY: Never commit to version control
  • DEBUG: Set to False in production
  • Requirements: Keep requirements.txt updated
  • App Structure: One app = one functionality
  • URL Names: Always use named URLs
  • Templates: Use template inheritance
  • Static Files: Organize by type (css, js, images)
Security First: Django has built-in security features - use them!

Next Session: Django ORM & CRUD

  • Django Models and ORM
  • Database migrations
  • CRUD operations (Create, Read, Update, Delete)
  • QuerySets and filtering
  • Model relationships (ForeignKey, ManyToMany)
  • Django Admin interface

Preparation: Complete Task 1 and 2. Review Python classes.

Questions & Discussion

Contact: JWilliams@Staff.newman.ac.uk

Office Hours: By appointment

Resources: Django Documentation, Django Girls Tutorial

Thank you for your attention!