Final Project: Building a Comprehensive Web Application
In this final lesson of the "Django for Python Developers" course, we will consolidate everything you've learned by building a comprehensive web application using Django. This project will not only reinforce your understanding of Django's core concepts but also give you hands-on experience in creating a fully functional web application.
Learning Objectives
By the end of this lesson, you will: - Understand how to plan and structure a web application. - Implement models, views, and templates to create a functional application. - Integrate user authentication and permissions. - Work with forms and handle user input. - Utilize Django’s built-in features for deployment.
Project Overview
For our final project, we will build a simple Task Management Application. This application will allow users to: - Register and log in. - Create, update, and delete tasks. - Mark tasks as complete. - Filter tasks by status (completed or pending).
Step 1: Planning the Application
Before diving into coding, it’s essential to plan your application. Here’s a high-level overview of the components we’ll need:
-
Models: Define the data structure in our application. - User (inherited from Django's User model) - Task
-
Views: Handle the logic of the application. - Task list view - Task detail view - Task create/edit view
-
Templates: Define how our application will look. - Base template - Task list template - Task form template
-
URLs: Map URLs to views.
Step 2: Setting Up the Project
First, let’s create a new Django project and a new app for our tasks.
django-admin startproject taskmanager
cd taskmanager
django-admin startapp tasks
This command will create a new Django project named taskmanager and a new app named tasks.
Step 3: Defining Models
Next, let’s define our models in tasks/models.py.
from django.db import models
from django.contrib.auth.models import User
class Task(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
completed = models.BooleanField(default=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
In this code:
- We define a Task model with fields for title, description, created_at, completed, and a foreign key to the User model.
- The __str__ method returns the title of the task, which is useful for representation in the admin interface.
Step 4: Registering Models with Admin
To manage our tasks, we need to register the model in the Django admin. In tasks/admin.py, add:
from django.contrib import admin
from .models import Task
admin.site.register(Task)
This allows us to manage tasks through the Django admin interface.
Step 5: Creating Views
Now let’s create views to handle displaying and manipulating tasks. In tasks/views.py, add:
from django.shortcuts import render, redirect
from .models import Task
from .forms import TaskForm
def task_list(request):
tasks = Task.objects.filter(user=request.user)
return render(request, 'tasks/task_list.html', {'tasks': tasks})
def task_create(request):
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
task = form.save(commit=False)
task.user = request.user
task.save()
return redirect('task_list')
else:
form = TaskForm()
return render(request, 'tasks/task_form.html', {'form': form})
In this code:
- task_list view retrieves tasks for the logged-in user and renders them in a template.
- task_create view handles the creation of new tasks. If the request method is POST, it processes the form; otherwise, it displays an empty form.
Step 6: Creating Forms
Next, we need a form for our tasks. Create a new file tasks/forms.py:
from django import forms
from .models import Task
class TaskForm(forms.ModelForm):
class Meta:
model = Task
fields = ['title', 'description']
This form uses Django's ModelForm to create a form based on the Task model. It will automatically generate fields for title and description.
Step 7: Creating Templates
Now, let’s create the templates for our application. Create a folder named templates/tasks in the tasks app directory and create the following files:
- task_list.html:
```html
{% extends 'base.html' %}
{% block content %}
Task List
-
{% for task in tasks %}
- {{ task.title }} - {% if task.completed %}Completed{% else %}Pending{% endif %} {% endfor %}
{% endblock %} ``` This template displays a list of tasks and includes a link to add a new task.
- task_form.html:
```html
{% extends 'base.html' %}
{% block content %}
Add Task
{% endblock %} ``` This template displays a form for creating or editing tasks.
- base.html: ```html
Task Manager
``` This is a simple base template that other templates will extend.
Step 8: Configuring URLs
Next, we need to configure URLs for our application. In tasks/urls.py, add:
from django.urls import path
from .views import task_list, task_create
urlpatterns = [
path('', task_list, name='task_list'),
path('task/new/', task_create, name='task_create'),
]
Now, include the tasks.urls in the main taskmanager/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('tasks.urls')),
]
Step 9: User Authentication
To enable user authentication, we will use Django's built-in authentication views. In taskmanager/urls.py, add:
from django.contrib.auth import views as auth_views
urlpatterns += [
path('login/', auth_views.LoginView.as_view(), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]
Step 10: Running the Application
Now that we’ve set everything up, run the following commands to make migrations and start the server:
python manage.py makemigrations
ython manage.py migrate
python manage.py runserver
Open your browser and navigate to http://127.0.0.1:8000/. You should see the task list page. You can log in, add tasks, and see them listed.
Common Mistakes and How to Avoid Them
- Not migrating the database: Always run
makemigrationsandmigrateafter modifying your models. - Forgetting to include CSRF tokens: Always include
{% csrf_token %}in your forms to prevent CSRF attacks. - Not checking user authentication: Ensure that views that require user authentication are protected.
Best Practices
- Structure your application logically: Keep your models, views, and templates organized within their respective directories.
- Use Django’s built-in features: Take advantage of Django’s built-in authentication and admin features to save time and effort.
- Test your application: Regularly test your application to catch bugs early.
Key Takeaways
- You have built a Task Management Application using Django, reinforcing your understanding of models, views, and templates.
- You learned how to implement user authentication and manage user-specific data.
- You gained experience in structuring a Django project and utilizing Django’s built-in features effectively.
Conclusion
Congratulations! You have completed the "Django for Python Developers" course. You now have a solid foundation in Django and are ready to explore more advanced topics or start building your own applications. The skills you have gained here will serve you well in your future programming endeavors. Keep practicing, and don’t hesitate to experiment with new features in Django to enhance your applications.
Exercises
Practice Exercises
- Add Task Detail View: Implement a view that displays the details of a specific task when clicked from the task list. Create a corresponding template to show the task's details.
- Edit Task Feature: Modify your application to allow users to edit existing tasks. Create a view and template for editing tasks.
- Mark Task as Complete: Implement a feature that allows users to mark tasks as completed. Update the task list to reflect the completion status.
- User Registration: Implement a registration view and template to allow new users to sign up for your application.
Assignment/Mini-Project
Create a Task Management Application with the following features: - User registration, login, and logout. - Create, edit, and delete tasks. - Mark tasks as complete or pending. - Filter tasks by status (completed or pending). - Ensure that each user can only see their own tasks.
Summary
- You built a comprehensive web application using Django.
- You learned to implement models, views, and templates for a functional application.
- User authentication was integrated using Django’s built-in features.
- You practiced creating and managing forms to handle user input.
- You gained experience in structuring a Django project and deploying it.
- Regular testing and following best practices are crucial for maintaining a healthy application.