Your First Step into Web Development: Building a Basic To-Do List with Django

Hello there, aspiring web developer! Ever wanted to build your own website or web application but felt overwhelmed by where to start? You’re in luck! Today, we’re going to take a fun and practical first step together: creating a simple To-Do List application using a powerful web framework called Django.

A To-Do List app is a fantastic project for beginners because it covers many fundamental concepts without being too complicated. By the end of this guide, you’ll have a basic application running that can display a list of tasks – a solid foundation for more complex projects!

What is Django?

Let’s start with the star of our show: Django.

Imagine you want to build a house. You could gather every single brick, piece of wood, and nail yourself, and design everything from scratch. Or, you could use a pre-built kit that provides you with walls, roofs, and windows, letting you focus on the interior design and unique touches.

Django is like that pre-built kit for websites. It’s a web framework (a toolkit of pre-written code) that helps you build robust and scalable web applications quickly, without having to reinvent the wheel for common web development tasks. It’s written in Python, a very beginner-friendly programming language.

Getting Started: Setting Up Your Environment

Before we dive into coding, we need to set up our workspace. Think of it as preparing your construction site!

Prerequisites

You’ll need a few things installed on your computer:

  • Python: Make sure you have Python 3 installed. You can download it from the official Python website.
  • pip: This is Python’s package installer, usually comes with Python. We’ll use it to install Django.
  • A Text Editor: Visual Studio Code, Sublime Text, Atom, or even a simple Notepad++ will work!

Creating a Virtual Environment

It’s good practice to create a virtual environment for each of your Python projects. This keeps the packages (like Django) for one project separate from others, preventing conflicts.

  1. Create a project folder:
    bash
    mkdir my_todo_project
    cd my_todo_project
  2. Create the virtual environment:
    bash
    python -m venv venv

    Explanation: python -m venv venv tells Python to create a new virtual environment named venv inside your project folder.
  3. Activate the virtual environment:
    • On Windows:
      bash
      .\venv\Scripts\activate
    • On macOS/Linux:
      bash
      source venv/bin/activate

      You’ll see (venv) appear at the start of your command prompt, indicating that your virtual environment is active.
  4. Install Django: Now, with your virtual environment active, install Django using pip.
    bash
    pip install django

Starting Your Django Project

With Django installed, let’s create our first Django project.

  1. Start a new project:
    bash
    django-admin startproject todo_project .

    Explanation:

    • django-admin is the command-line tool Django provides.
    • startproject is the command to create a new project.
    • todo_project is the name of our main project.
    • . (the dot) tells Django to create the project files in the current directory, instead of creating another nested folder.

    After this, you’ll see a structure like this:
    my_todo_project/
    ├── venv/
    ├── todo_project/
    │ ├── __init__.py
    │ ├── settings.py # Project settings
    │ ├── urls.py # Project URL definitions
    │ └── wsgi.py
    ├── manage.py # A utility script to interact with your project

    2. Run the development server: Let’s make sure everything is set up correctly.
    bash
    python manage.py runserver

    You should see output similar to:
    “`
    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.
    September 10, 2023 – 10:00:00
    Django version 4.2.5, using settings ‘todo_project.settings’
    Starting development server at http://127.0.0.1:8000/
    Quit the server with CONTROL-C.
    ``
    Open your web browser and go to
    http://127.0.0.1:8000/. You should see a "The install worked successfully! Congratulations!" page. This means your Django project is up and running! PressCTRL+C` in your terminal to stop the server for now.

Creating a Django App

In Django, projects are made of smaller, reusable components called apps. Think of the todo_project as the entire house, and an app as a specific room (like the kitchen or bedroom) that has a specific purpose. We’ll create an app specifically for our To-Do list functionality.

  1. Create a new app:
    bash
    python manage.py startapp todo

    This creates a new folder named todo inside my_todo_project/ with its own set of files.

  2. Register your app: Django needs to know about your new todo app. Open todo_project/settings.py and add 'todo' to the INSTALLED_APPS list.

    “`python

    todo_project/settings.py

    INSTALLED_APPS = [
    ‘django.contrib.admin’,
    ‘django.contrib.auth’,
    ‘django.contrib.contenttypes’,
    ‘django.contrib.sessions’,
    ‘django.contrib.messages’,
    ‘django.contrib.staticfiles’,
    ‘todo’, # <— Add your app here
    ]
    “`

Defining Your To-Do Model

Now, let’s define what a “task” in our To-Do list should look like. In Django, we do this using models. A model is like a blueprint for the data you want to store in your database. Django’s models also provide an easy way to interact with your database without writing complex SQL code (this is called an ORM – Object-Relational Mapper).

  1. Open todo/models.py and define your Task model:

    “`python

    todo/models.py

    from django.db import models

    class Task(models.Model):
    title = models.CharField(max_length=200) # A short text for the task name
    description = models.TextField(blank=True, null=True) # Longer text, optional
    created_at = models.DateTimeField(auto_now_add=True) # Date and time created, set automatically
    completed = models.BooleanField(default=False) # True if task is done, False otherwise

    def __str__(self):
        return self.title # How a Task object will be displayed (e.g., in the admin)
    

    ``
    *Explanation:*
    *
    models.Modelmeans ourTaskclass inherits all the good stuff from Django's model system.
    *
    title: ACharField(character field) for short text, with a maximum length.
    *
    description: ATextFieldfor longer text.blank=Truemeans it's not required to fill this field in forms, andnull=Trueallows the database field to be empty.
    *
    created_at: ADateTimeFieldthat automatically sets the current date and time when a task is created (auto_now_add=True).
    *
    completed: ABooleanField(true/false) with a default value ofFalse.
    *
    str(self)`: This special method defines how an object of this model will be represented as a string. It’s helpful for displaying objects in the admin panel.

  2. Make migrations: After defining your model, you need to tell Django to create the necessary tables in your database.
    bash
    python manage.py makemigrations

    This command creates migration files that describe the changes to your database schema. You’ll see something like Migrations for 'todo': 0001_initial.py.

  3. Apply migrations: Now, apply those changes to your actual database.
    bash
    python manage.py migrate

    This command executes the migration files, creating the Task table (and other default Django tables) in your database.

Making It Visible: The Admin Panel

Django comes with a powerful, ready-to-use admin panel. It’s a web interface that allows you to manage your data easily. Let’s make our Task model accessible through it.

  1. Create a superuser: This is an administrator account for your Django project.
    bash
    python manage.py createsuperuser

    Follow the prompts to create a username, email (optional), and password.

  2. Register your model: Open todo/admin.py and register your Task model:
    “`python
    # todo/admin.py

    from django.contrib import admin
    from .models import Task

    admin.site.register(Task)
    “`

  3. Run the server again:
    bash
    python manage.py runserver

    Go to http://127.0.0.1:8000/admin/ in your browser. Log in with the superuser credentials you just created. You should now see “Tasks” under the “TODO” section. Click on “Tasks” to add a new task, view, or edit existing ones! This is a great way to quickly add some sample data.

Basic Views and URLs

Now that we can store tasks, let’s display them to users! This involves two main components: views and URLs.

  • A view is a Python function (or class) that takes a web request and returns a web response. It’s like the “brain” that decides what data to get from the model and what to show on the webpage.
  • A URL (Uniform Resource Locator) is the web address that users type into their browser. We need to tell Django which view should handle which URL.

  • Create a view: Open todo/views.py and add a function to display tasks:
    “`python
    # todo/views.py

    from django.shortcuts import render
    from .models import Task # Import our Task model

    def task_list(request):
    tasks = Task.objects.all().order_by(‘-created_at’) # Get all tasks, newest first
    return render(request, ‘todo/task_list.html’, {‘tasks’: tasks})
    ``
    *Explanation:*
    *
    task_list(request): This is our view function. It takes arequestobject as an argument.
    *
    tasks = Task.objects.all().order_by(‘-created_at’): This line uses ourTaskmodel to fetch all tasks from the database and orders them by their creation date, with the newest first (thesign means descending order).
    *
    render(request, ‘todo/task_list.html’, {‘tasks’: tasks}): This is a shortcut function that combines a request, a **template** (an HTML file), and a dictionary of data ({‘tasks’: tasks}) into an HTTP response. It means "render thetask_list.htmlfile, and make thetasks` variable available inside it.”

  • Define URLs for the app: Create a new file inside your todo app folder named urls.py.

    “`python

    todo/urls.py

    from django.urls import path
    from . import views # Import our views from the current app

    urlpatterns = [
    path(”, views.task_list, name=’task_list’), # Our root URL for the app
    ]
    ``
    *Explanation:*
    *
    path(”, views.task_list, name=’task_list’): This maps the empty path (meaninghttp://127.0.0.1:8000/todo/if we set it up that way) to ourtask_listview.name=’task_list’` gives this URL a memorable name for later use.

  • Include app URLs in the project’s URLs: We need to tell the main todo_project about the URLs defined in our todo app. Open todo_project/urls.py.

    “`python

    todo_project/urls.py

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

    urlpatterns = [
    path(‘admin/’, admin.site.urls),
    path(‘todo/’, include(‘todo.urls’)), # <— Add this line
    ]
    ``
    *Explanation:*
    *
    path(‘todo/’, include(‘todo.urls’)): This tells Django that any URL starting withtodo/should be handed over to the URL patterns defined in ourtodoapp'surls.py. So, if you go tohttp://127.0.0.1:8000/todo/, it will use thetask_list` view we defined.

Creating a Simple Template

Finally, let’s create the HTML file that our task_list view will render to display the tasks. Django uses templates to separate Python code logic from the presentation (HTML).

  1. Create a templates directory: Inside your todo app folder, create a new folder named templates. Inside templates, create another folder named todo. This structure (app_name/templates/app_name/) is a best practice to avoid conflicts if you have multiple apps with similarly named templates.
    my_todo_project/
    ├── ...
    ├── todo/
    │ ├── migrations/
    │ ├── templates/
    │ │ └── todo/ # <--- New folder
    │ │ └── task_list.html # <--- New file
    │ ├── __init__.py
    │ ├── admin.py
    │ ├── apps.py
    │ ├── models.py
    │ ├── tests.py
    │ ├── urls.py # <--- New file
    │ └── views.py
    ├── ...

  2. Create task_list.html: Open todo/templates/todo/task_list.html and add this HTML:
    “`html

    <!DOCTYPE html>




    My To-Do List


    My To-Do List

    {% if tasks %} {# Check if there are any tasks #}
        <ul>
            {% for task in tasks %} {# Loop through each task #}
                <li class="{% if task.completed %}completed{% endif %}">
                    <h2>{{ task.title }}</h2>
                    {% if task.description %}
                        <p class="description">{{ task.description }}</p>
                    {% endif %}
                    <small>Created: {{ task.created_at|date:"M d, Y" }}</small><br>
                    <small>Status: {% if task.completed %}Completed{% else %}Pending{% endif %}</small>
                </li>
            {% endfor %}
        </ul>
    {% else %} {# If no tasks #}
        <p>No tasks yet! Time to add some in the admin panel.</p>
    {% endif %}
    



    ``
    *Explanation:*
    *
    {% if tasks %}and{% for task in tasks %}: These are Django's **template tags**. They allow you to add basic logic (likeifstatements andforloops) directly into your HTML.
    *
    {{ task.title }}: This is a **template variable**. It displays the value of thetitleattribute of thetaskobject passed from the view.
    *
    {{ task.created_at|date:”M d, Y” }}: This uses a **template filter** (|date:”M d, Y”`) to format the date nicely.

Seeing Your To-Do List in Action!

  1. Run the server again (if it’s not already running):
    bash
    python manage.py runserver
  2. Open your browser and navigate to http://127.0.0.1:8000/todo/.

You should now see your very own To-Do List, displaying any tasks you added through the admin panel! How cool is that?

Conclusion

Congratulations! You’ve just taken a significant step into the world of web development with Django. In this guide, you’ve learned to:

  • Set up a Django project and app.
  • Define a data model (Task).
  • Manage your data using the Django admin panel.
  • Create a view to fetch data.
  • Map URLs to your views.
  • Display data using Django templates.

This is just the beginning! From here, you can expand this application by adding features like:
* Forms to add new tasks directly from the main page.
* Buttons to mark tasks as completed.
* User authentication so different users have their own To-Do lists.

Keep exploring, keep building, and have fun on your coding journey!


Comments

Leave a Reply