Django for Beginners: Building Your First Simple CRUD Application

Hello future web developers! Are you curious about building websites but feel a bit overwhelmed? You’re in the right place! Today, we’re going to dive into Django, a powerful yet friendly web framework that uses Python. We’ll build a “CRUD” application, which is a fantastic way to understand how web applications handle information.

What is Django?

Imagine you want to build a house. Instead of crafting every brick, pipe, and wire yourself, you’d use a construction kit with pre-made components, tools, and a clear plan. That’s essentially what Django is for web development!

Django is a “web framework” built with Python. A web framework is a collection of tools and components that help you build websites faster and more efficiently. It handles many of the repetitive tasks involved in web development, letting you focus on the unique parts of your application. Django is known for its “batteries-included” philosophy, meaning it comes with a lot of features already built-in, like an administrative interface, an Object-Relational Mapper (ORM), and template system.

What is CRUD?

CRUD is an acronym that stands for:

  • Create: Adding new information (like adding a new post to a blog).
  • Read: Viewing existing information (like reading a blog post).
  • Update: Changing existing information (like editing a blog post).
  • Delete: Removing information (like deleting a blog post).

These are the fundamental operations for almost any application that manages data, and mastering them in Django is a huge step! We’ll build a simple “Task Manager” where you can create, view, update, and delete tasks.


1. Setting Up Your Development Environment

Before we start coding, we need to set up our workspace.

Install Python and pip

Make sure you have Python installed on your computer. You can download it from python.org. Python usually comes with pip, which is Python’s package installer (a tool to install other Python libraries).

Create a Virtual Environment

It’s a good practice to use a “virtual environment” for each project. Think of it as an isolated box for your project’s dependencies. This prevents conflicts between different projects that might use different versions of the same library.

Open your terminal or command prompt and run these commands:

python -m venv myenv

This creates a new folder named myenv (you can choose any name) which will hold your virtual environment.

Next, activate it:

  • On Windows:
    bash
    .\myenv\Scripts\activate
  • On macOS/Linux:
    bash
    source myenv/bin/activate

    You’ll see (myenv) at the beginning of your command prompt, indicating the virtual environment is active.

Install Django

With your virtual environment active, let’s install Django:

pip install django

2. Starting Your Django Project and App

In Django, a “project” is the entire web application, and “apps” are smaller, reusable modules within that project (e.g., a “blog” app, a “users” app).

Create a Django Project

Navigate to where you want to store your project and run:

django-admin startproject taskmanager .

Here, taskmanager is the name of our project. The . at the end tells Django to create the project files in the current directory, rather than creating an extra taskmanager folder inside another taskmanager folder.

Create a Django App

Now, let’s create our first app within the project:

python manage.py startapp tasks

This creates a new folder named tasks with several files inside. This tasks app will handle everything related to our tasks (like creating, viewing, and managing them).

Register Your App

Django needs to know about the new app. Open taskmanager/settings.py (inside your taskmanager folder) and add 'tasks' to the INSTALLED_APPS list:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'tasks', # Our new app!
]

3. Defining Your Data (Models)

In Django, you describe how your data looks using “models.” A model is a Python class that defines the structure of your data and tells Django how to store it in a database.

Open tasks/models.py and let’s define our Task model:

from django.db import models

class Task(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField(blank=True, null=True)
    completed = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title
  • title: A short text field for the task name. max_length is required.
  • description: A longer text field. blank=True means it can be left empty, null=True means the database can store NULL for this field.
  • completed: A true/false field, default=False means a new task is not completed by default.
  • created_at: A date and time field that automatically gets set when a task is created.
  • def __str__(self): This special method tells Django how to represent a Task object as a string, which is helpful in the Django admin and when debugging.

Make and Apply Migrations

After defining your model, you need to tell Django to create the corresponding table in your database. This is done with “migrations.” Migrations are Django’s way of propagating changes you make to your models into your database schema.

In your terminal (with the virtual environment active), run:

python manage.py makemigrations
python manage.py migrate

makemigrations creates migration files (instructions for changes), and migrate applies those changes to your database.


4. Making Things Happen (Views)

“Views” are Python functions or classes that receive web requests and return web responses. They are the heart of your application’s logic. For CRUD operations, Django provides helpful “Class-Based Views” (CBVs) that simplify common tasks.

Open tasks/views.py and add these views:

from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from .models import Task

class TaskListView(ListView):
    model = Task
    template_name = 'tasks/task_list.html' # HTML file to display list of tasks
    context_object_name = 'tasks' # Name for the list of tasks in the template

class TaskDetailView(DetailView):
    model = Task
    template_name = 'tasks/task_detail.html' # HTML file to display a single task
    context_object_name = 'task'

class TaskCreateView(CreateView):
    model = Task
    template_name = 'tasks/task_form.html' # HTML form for creating a task
    fields = ['title', 'description', 'completed'] # Fields to show in the form
    success_url = reverse_lazy('task_list') # Where to go after successfully creating a task

class TaskUpdateView(UpdateView):
    model = Task
    template_name = 'tasks/task_form.html' # HTML form for updating a task
    fields = ['title', 'description', 'completed']
    success_url = reverse_lazy('task_list')

class TaskDeleteView(DeleteView):
    model = Task
    template_name = 'tasks/task_confirm_delete.html' # HTML page to confirm deletion
    success_url = reverse_lazy('task_list') # Where to go after successfully deleting a task
  • ListView: Displays a list of objects.
  • DetailView: Displays a single object’s details.
  • CreateView: Handles displaying a form and saving a new object.
  • UpdateView: Handles displaying a form and updating an existing object.
  • DeleteView: Handles confirming deletion and deleting an object.
  • reverse_lazy(): A function that helps Django figure out the URL name from our urls.py file, even before the URLs are fully loaded.

5. Creating the User Interface (Templates)

Templates are HTML files that Django uses to display information to the user. They can include special Django syntax to show data from your views.

First, tell Django where to find your templates. Create a folder named templates inside your tasks app folder (tasks/templates/). Inside tasks/templates/, create another folder named tasks/ (tasks/templates/tasks/). This structure helps organize templates for different apps.

Your folder structure should look like this:

taskmanager/
├── taskmanager/
   ├── ...
├── tasks/
   ├── migrations/
   ├── templates/
      └── tasks/  <-- Our templates will go here!
   ├── __init__.py
   ├── admin.py
   ├── apps.py
   ├── models.py
   ├── tests.py
   └── views.py
├── manage.py
└── db.sqlite3

Now, let’s create the basic HTML files inside tasks/templates/tasks/:

task_list.html (Read – List all tasks)

<!-- tasks/templates/tasks/task_list.html -->
<h1>My Task List</h1>
<a href="{% url 'task_create' %}">Create New Task</a>

<ul>
    {% for task in tasks %}
    <li>
        <a href="{% url 'task_detail' task.pk %}">{{ task.title }}</a>
        - {{ task.description|default:"No description" }}
        - Status: {% if task.completed %}Completed{% else %}Pending{% endif %}
        - <a href="{% url 'task_update' task.pk %}">Edit</a>
        - <a href="{% url 'task_delete' task.pk %}">Delete</a>
    </li>
    {% empty %}
    <li>No tasks yet!</li>
    {% endfor %}
</ul>

task_detail.html (Read – View a single task)

<!-- tasks/templates/tasks/task_detail.html -->
<h1>Task: {{ task.title }}</h1>
<p>Description: {{ task.description|default:"No description" }}</p>
<p>Status: {% if task.completed %}Completed{% else %}Pending{% endif %}</p>
<p>Created: {{ task.created_at }}</p>

<a href="{% url 'task_update' task.pk %}">Edit Task</a> |
<a href="{% url 'task_delete' task.pk %}">Delete Task</a> |
<a href="{% url 'task_list' %}">Back to List</a>

task_form.html (Create & Update)

<!-- tasks/templates/tasks/task_form.html -->
<h1>{% if form.instance.pk %}Edit Task{% else %}Create New Task{% endif %}</h1>

<form method="post">
    {% csrf_token %} {# Security token required by Django for forms #}
    {{ form.as_p }} {# Renders form fields as paragraphs #}
    <button type="submit">Save Task</button>
</form>

<a href="{% url 'task_list' %}">Cancel</a>

task_confirm_delete.html (Delete)

<!-- tasks/templates/tasks/task_confirm_delete.html -->
<h1>Delete Task</h1>
<p>Are you sure you want to delete "{{ task.title }}"?</p>

<form method="post">
    {% csrf_token %}
    <button type="submit">Yes, delete</button>
    <a href="{% url 'task_list' %}">No, go back</a>
</form>

6. Connecting URLs (URL Routing)

URL routing is how Django maps incoming web addresses (URLs) to the correct “views” in your application.

First, create a urls.py file inside your tasks app folder (tasks/urls.py).

from django.urls import path
from .views import TaskListView, TaskDetailView, TaskCreateView, TaskUpdateView, TaskDeleteView

urlpatterns = [
    path('', TaskListView.as_view(), name='task_list'), # Home page, lists all tasks
    path('task/<int:pk>/', TaskDetailView.as_view(), name='task_detail'), # View a single task
    path('task/new/', TaskCreateView.as_view(), name='task_create'), # Create a new task
    path('task/<int:pk>/edit/', TaskUpdateView.as_view(), name='task_update'), # Edit an existing task
    path('task/<int:pk>/delete/', TaskDeleteView.as_view(), name='task_delete'), # Delete a task
]
  • path('', ...): Matches the base URL of this app.
  • path('task/<int:pk>/', ...): Matches URLs like /task/1/ or /task/5/. <int:pk> captures the task’s primary key (a unique ID) and passes it to the view.
  • name='...': Gives a unique name to each URL pattern, making it easier to refer to them in templates and views.

Next, you need to include these app URLs into your project’s main urls.py. Open taskmanager/urls.py:

from django.contrib import admin
from django.urls import path, include # Make sure 'include' is imported

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('tasks.urls')), # Include our tasks app's URLs here
]

Now, when someone visits your website’s root URL (e.g., http://127.0.0.1:8000/), Django will direct that request to our tasks app’s urls.py file.


7. Running Your Application

You’ve done a lot of work! Let’s see it in action.

In your terminal, make sure your virtual environment is active, and you are in the directory where manage.py is located. Then run:

python manage.py runserver

You should see output indicating the server is running, usually at http://127.0.0.1:8000/. Open this address in your web browser.

You should now see your “My Task List” page! Try to:
* Click “Create New Task” to add a task (Create).
* See the task appear in the list (Read – List).
* Click on a task’s title to view its details (Read – Detail).
* Click “Edit” to change a task (Update).
* Click “Delete” to remove a task (Delete).

Congratulations! You’ve successfully built your first simple CRUD application using Django.


Conclusion

You’ve just built a complete web application that can manage data – a huge accomplishment for a beginner! You learned about:

  • Django projects and apps: How to organize your code.
  • Models: Defining your data structure.
  • Migrations: Syncing models with your database.
  • Views: Handling requests and responses using Django’s powerful Class-Based Views.
  • Templates: Creating dynamic HTML pages.
  • URL Routing: Connecting web addresses to your application logic.

This is just the beginning of your Django journey. There’s so much more to explore, like user authentication, forms, static files, and deploying your application. Keep practicing, keep building, and don’t be afraid to experiment! Happy coding!


Comments

Leave a Reply