Introduction

In this section, we will explore how to build web applications using the Django framework. Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It is known for its "batteries-included" philosophy, which means it comes with many built-in features to handle common web development tasks.

Key Concepts

  1. Django Project vs. Django App:

    • Project: The entire web application, including settings and configurations.
    • App: A web application that does something, e.g., a blog, a forum, or a poll.
  2. MVC Pattern:

    • Model: Manages the data and business logic.
    • View: Manages the user interface and presentation.
    • Controller: Manages the input and interaction.
  3. URL Routing:

    • Maps URLs to views.
  4. Templates:

    • HTML files mixed with Django Template Language (DTL).
  5. Forms:

    • Handle user input and validation.

Setting Up a Django Project

Step 1: Install Django

pip install django

Step 2: Create a Django Project

django-admin startproject myproject

Step 3: Create a Django App

cd myproject
python manage.py startapp myapp

Step 4: Configure the Project

Edit myproject/settings.py to include your new app:

INSTALLED_APPS = [
    ...
    'myapp',
]

URL Routing

Step 1: Define URLs in the App

Create a file myapp/urls.py:

from django.urls import path
from . import views

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

Step 2: Include App URLs in the Project

Edit myproject/urls.py:

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

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

Views

Step 1: Create a View

Edit myapp/views.py:

from django.http import HttpResponse

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

Templates

Step 1: Create a Template Directory

Create a directory myapp/templates/myapp/ and add an index.html file:

<!DOCTYPE html>
<html>
<head>
    <title>My App</title>
</head>
<body>
    <h1>Hello, world. You're at the myapp index.</h1>
</body>
</html>

Step 2: Update the View to Use the Template

Edit myapp/views.py:

from django.shortcuts import render

def index(request):
    return render(request, 'myapp/index.html')

Models

Step 1: Define a Model

Edit myapp/models.py:

from django.db import models

class Item(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

Step 2: Create and Apply Migrations

python manage.py makemigrations
python manage.py migrate

Step 3: Register the Model in the Admin

Edit myapp/admin.py:

from django.contrib import admin
from .models import Item

admin.site.register(Item)

Forms

Step 1: Create a Form

Edit myapp/forms.py:

from django import forms
from .models import Item

class ItemForm(forms.ModelForm):
    class Meta:
        model = Item
        fields = ['name', 'description']

Step 2: Use the Form in a View

Edit myapp/views.py:

from django.shortcuts import render, redirect
from .forms import ItemForm

def create_item(request):
    if request.method == 'POST':
        form = ItemForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('index')
    else:
        form = ItemForm()
    return render(request, 'myapp/create_item.html', {'form': form})

Step 3: Create a Template for the Form

Create myapp/templates/myapp/create_item.html:

<!DOCTYPE html>
<html>
<head>
    <title>Create Item</title>
</head>
<body>
    <h1>Create Item</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Save</button>
    </form>
</body>
</html>

Practical Exercise

Task

  1. Create a new Django project and app.
  2. Define a model for a simple blog post with fields for title, content, and publication date.
  3. Create views to list all blog posts and to create a new blog post.
  4. Use templates to render the views.
  5. Implement forms for creating new blog posts.

Solution

  1. Create Project and App:
django-admin startproject blogproject
cd blogproject
python manage.py startapp blogapp
  1. Define Model:

Edit blogapp/models.py:

from django.db import models

class BlogPost(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    pub_date = models.DateTimeField('date published')
  1. Create and Apply Migrations:
python manage.py makemigrations
python manage.py migrate
  1. Register Model in Admin:

Edit blogapp/admin.py:

from django.contrib import admin
from .models import BlogPost

admin.site.register(BlogPost)
  1. Define URLs:

Edit blogapp/urls.py:

from django.urls import path
from . import views

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

Include app URLs in blogproject/urls.py:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blogapp/', include('blogapp.urls')),
]
  1. Create Views:

Edit blogapp/views.py:

from django.shortcuts import render, redirect
from .models import BlogPost
from .forms import BlogPostForm

def index(request):
    posts = BlogPost.objects.all()
    return render(request, 'blogapp/index.html', {'posts': posts})

def create_post(request):
    if request.method == 'POST':
        form = BlogPostForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('index')
    else:
        form = BlogPostForm()
    return render(request, 'blogapp/create_post.html', {'form': form})
  1. Create Forms:

Edit blogapp/forms.py:

from django import forms
from .models import BlogPost

class BlogPostForm(forms.ModelForm):
    class Meta:
        model = BlogPost
        fields = ['title', 'content', 'pub_date']
  1. Create Templates:

Create blogapp/templates/blogapp/index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Blog Posts</title>
</head>
<body>
    <h1>Blog Posts</h1>
    <ul>
        {% for post in posts %}
            <li>{{ post.title }} - {{ post.pub_date }}</li>
        {% endfor %}
    </ul>
    <a href="{% url 'create_post' %}">Create New Post</a>
</body>
</html>

Create blogapp/templates/blogapp/create_post.html:

<!DOCTYPE html>
<html>
<head>
    <title>Create Blog Post</title>
</head>
<body>
    <h1>Create Blog Post</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Save</button>
    </form>
</body>
</html>

Conclusion

In this section, we covered the basics of building web applications with Django. We learned how to set up a Django project and app, define models, create views, use templates, and handle forms. By completing the practical exercise, you should now have a good understanding of how to build a simple web application using Django. In the next module, we will delve into data science with Python, starting with an introduction to data science concepts and tools.

Python Programming Course

Module 1: Introduction to Python

Module 2: Control Structures

Module 3: Functions and Modules

Module 4: Data Structures

Module 5: Object-Oriented Programming

Module 6: File Handling

Module 7: Error Handling and Exceptions

Module 8: Advanced Topics

Module 9: Testing and Debugging

Module 10: Web Development with Python

Module 11: Data Science with Python

Module 12: Final Project

© Copyright 2024. All rights reserved