Skip to main content

Django Introduction

What is Django?

Django logo

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It was created in the mid-2000s by experienced developers who were working at a newspaper website. Django was designed to make common web development tasks fast and easy, allowing developers to focus on the unique aspects of their applications rather than reinventing the wheel.

Django follows the "batteries-included" philosophy, meaning it comes with many built-in features that you would normally have to build yourself or integrate from third-party packages in other frameworks. These include:

  • Authentication system
  • Admin interface
  • ORM (Object-Relational Mapper)
  • Form handling
  • Template engine
  • Internationalization
  • Security features

Why Use Django?

Django has several advantages that make it a popular choice for web development:

  1. Rapid Development: Django's "batteries-included" approach means you can build applications quickly without writing everything from scratch.

  2. Security: Django has built-in protections against many common security threats like SQL injection, cross-site scripting, cross-site request forgery, and clickjacking.

  3. Scalability: Many high-traffic websites use Django, including Instagram, Pinterest, and Disqus. It's designed to scale well.

  4. Versatility: Django can be used to build almost any type of website, from content management systems and wikis to social networks and news sites.

  5. DRY (Don't Repeat Yourself): Django encourages the reuse of code, which makes your applications more maintainable.

Django's Architecture: MVT Pattern

Django follows a slightly modified version of the traditional MVC (Model-View-Controller) architectural pattern called MVT (Model-View-Template):

  • Model: Defines your data structure and handles database operations
  • View: Contains the business logic and handles user requests
  • Template: Manages the presentation layer (HTML rendering)

This separation of concerns makes your code more organized and easier to maintain.

Setting Up Your Django Environment

Before we can start building with Django, we need to set up our development environment. This involves installing Python, creating a virtual environment, and installing Django.

Step 1: Install Python

Django is a Python framework, so you'll need Python installed on your system. Django 4.x requires Python 3.8 or higher.

You can check if Python is installed by running:

bash
python --version
# or
python3 --version

If Python is not installed, download and install it from python.org.

Step 2: Create a Virtual Environment

Virtual environments allow you to have isolated Python environments for different projects. This helps avoid package conflicts.

bash
# Create a new virtual environment
python -m venv django_env

# Activate the virtual environment
# On Windows
django_env\Scripts\activate

# On macOS/Linux
source django_env/bin/activate

When the virtual environment is activated, you'll see its name in your terminal prompt.

Step 3: Install Django

With your virtual environment activated, install Django using pip:

bash
pip install django

You can verify the installation by checking the Django version:

bash
python -m django --version

Creating Your First Django Project

Now that we have our environment set up, let's create our first Django project.

Step 1: Create a New Project

bash
django-admin startproject mysite

This command creates a directory structure for your project:

mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
  • manage.py: A command-line utility for interacting with your project
  • init.py: An empty file that tells Python this directory should be treated as a package
  • settings.py: Contains all the configuration for your project
  • urls.py: The URL declarations for your project
  • asgi.py: An entry-point for ASGI-compatible web servers
  • wsgi.py: An entry-point for WSGI-compatible web servers

Step 2: Run the Development Server

Navigate to your project directory and start the development server:

bash
cd mysite
python manage.py runserver

You should see output similar to this:

Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
July 14, 2023 - 15:50:53
Django version 4.2, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Open your browser and go to http://127.0.0.1:8000/. You should see Django's default success page:

Django Success Page

Step 3: Create an App

Django projects are composed of one or more apps. An app is a web application that does something – e.g., a blog system, a database of public records, or a simple poll application.

Let's create a simple poll app:

bash
python manage.py startapp polls

This creates another directory structure:

polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py

Step 4: Write Your First View

Open polls/views.py and add the following code:

python
from django.http import HttpResponse

def index(request):
return HttpResponse("Hello, world. You're at the polls index.")

Next, create a file called urls.py in the polls directory and add the following code:

python
from django.urls import path
from . import views

urlpatterns = [
path('', views.index, name='index'),
]

Then, modify the root URLconf (mysite/urls.py) to include our polls app:

python
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]

Step 5: See Your View in Action

Start the development server again and navigate to http://127.0.0.1:8000/polls/. You should see:

Hello, world. You're at the polls index.

Congratulations! You've created your first Django view.

Django Project Structure: A Real-world Example

Let's consider a simple blog application to understand how Django's components work together in a real-world scenario:

Models (Data Structure)

In blog/models.py:

python
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)

def __str__(self):
return self.title

This defines a blog post with a title, content, date, and author.

Views (Business Logic)

In blog/views.py:

python
from django.shortcuts import render
from .models import Post

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

def about(request):
return render(request, 'blog/about.html', {'title': 'About'})

These views retrieve data from the database and pass it to templates for rendering.

Templates (Presentation)

In blog/templates/blog/home.html:

html
{% extends "blog/base.html" %}
{% block content %}
{% for post in posts %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="#">{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
</div>
<h2><a class="article-title" href="#">{{ post.title }}</a></h2>
<p class="article-content">{{ post.content }}</p>
</div>
</article>
{% endfor %}
{% endblock content %}

This template displays all blog posts in a list.

URLs (Routing)

In blog/urls.py:

python
from django.urls import path
from . import views

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

These URL patterns map URLs to views.

Key Django Concepts

1. Models and the ORM

Django's ORM (Object-Relational Mapper) lets you define your data model in Python code rather than SQL. It provides a high-level, object-oriented interface to your database.

python
# Creating a new post
new_post = Post(title='Django is awesome', content='A detailed post about Django...', author=user)
new_post.save()

# Querying the database
recent_posts = Post.objects.filter(date_posted__year=2023).order_by('-date_posted')

2. Django Admin

Django comes with an automatic admin interface that reads metadata from your models to provide a powerful and production-ready interface for managing your content.

To use the admin interface:

  1. Create a superuser:
bash
python manage.py createsuperuser
  1. Register your models in admin.py:
python
from django.contrib import admin
from .models import Post

admin.site.register(Post)
  1. Access the admin interface at http://127.0.0.1:8000/admin/

3. Forms and Validation

Django provides a form library that handles form rendering, validation, and processing:

python
from django import forms
from .models import Post

class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'content']

This automatically generates form fields and validation for your model.

4. Authentication

Django includes a full-featured authentication system:

python
from django.contrib.auth.decorators import login_required

@login_required
def create_post(request):
# Only authenticated users can access this view
# ...

Summary

In this introduction to Django, we've explored:

  • What Django is and why it's a popular choice for web development
  • Django's MVT architecture (Model-View-Template)
  • How to set up a Django development environment
  • Creating your first Django project and app
  • Django's core components in a real-world example
  • Key Django concepts like the ORM, admin interface, forms, and authentication

Django's comprehensive feature set, robust security measures, and emphasis on developer productivity make it an excellent choice for building web applications of all sizes. By following Django's conventions and utilizing its built-in tools, you can develop sophisticated web applications efficiently while maintaining clean, maintainable code.

Further Resources

  1. Official Django Documentation
  2. Django for Beginners by William S. Vincent
  3. Django Girls Tutorial
  4. MDN Django Web Framework

Practice Exercises

  1. Create a simple Django app that displays a list of your favorite books or movies.
  2. Extend the polls application we started by adding models for questions and choices.
  3. Build a simple blog application with CRUD functionality (Create, Read, Update, Delete).
  4. Create a custom user registration and login system using Django's authentication system.
  5. Implement a RESTful API using Django REST Framework for an existing Django application.

Each of these exercises will help reinforce the concepts covered in this introduction and build your confidence with Django development.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)