how-to-create-a-simple-crud-application-with-django.html

How to Create a Simple CRUD Application with Django

Creating web applications can feel daunting, especially if you're new to web development. However, with a framework like Django, building a simple CRUD (Create, Read, Update, Delete) application becomes a lot easier. In this article, we will walk through the steps to create a basic CRUD application using Django, covering everything from project setup to deploying your app.

What is CRUD?

CRUD stands for Create, Read, Update, and Delete—the four basic operations that you can perform on data. These operations form the foundation of most web applications, as they allow users to manage data effectively. Whether you're building a blog, a task manager, or an inventory system, understanding how to implement these CRUD operations is essential.

Use Cases for a CRUD Application

CRUD applications are ubiquitous in web development. Here are a few common use cases:

  • Blog Platforms: Manage posts, categories, and comments.
  • Task Management Tools: Create, view, update, and delete tasks.
  • Inventory Systems: Track products, suppliers, and orders.

Setting Up Your Django Project

Step 1: Install Django

Before we get started, ensure you have Python installed on your machine. You can check if Python is installed by running:

python --version

To install Django, use pip:

pip install django

Step 2: Create a New Django Project

Once Django is installed, create a new project by running:

django-admin startproject mycrudapp

Navigate into your project directory:

cd mycrudapp

Step 3: Create a Django App

Django projects are made up of apps that encapsulate specific functionalities. Create a new app called tasks:

python manage.py startapp tasks

Step 4: Update Settings

Add your new app to the project settings. Open mycrudapp/settings.py and add 'tasks', to the INSTALLED_APPS list:

INSTALLED_APPS = [
    ...
    'tasks',
]

Building the CRUD Functionality

Step 5: Define the Model

In your tasks app, open models.py and define a model for your tasks:

from django.db import models

class Task(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()
    completed = models.BooleanField(default=False)

    def __str__(self):
        return self.title

Step 6: Make Migrations

Run the following commands to create and apply migrations for your new model:

python manage.py makemigrations
python manage.py migrate

Step 7: Create the Admin Interface

To manage tasks easily, register your model in the Django admin. Open tasks/admin.py and add:

from django.contrib import admin
from .models import Task

admin.site.register(Task)

Step 8: Create Views for CRUD Operations

Next, we’ll create views to handle our CRUD operations. Open tasks/views.py and add the following code:

from django.shortcuts import render, redirect, get_object_or_404
from .models import Task
from .forms import TaskForm

def task_list(request):
    tasks = Task.objects.all()
    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():
            form.save()
            return redirect('task_list')
    else:
        form = TaskForm()
    return render(request, 'tasks/task_form.html', {'form': form})

def task_update(request, pk):
    task = get_object_or_404(Task, pk=pk)
    if request.method == 'POST':
        form = TaskForm(request.POST, instance=task)
        if form.is_valid():
            form.save()
            return redirect('task_list')
    else:
        form = TaskForm(instance=task)
    return render(request, 'tasks/task_form.html', {'form': form})

def task_delete(request, pk):
    task = get_object_or_404(Task, pk=pk)
    if request.method == 'POST':
        task.delete()
        return redirect('task_list')
    return render(request, 'tasks/task_confirm_delete.html', {'task': task})

Step 9: Create Forms

Create a form for your tasks in tasks/forms.py:

from django import forms
from .models import Task

class TaskForm(forms.ModelForm):
    class Meta:
        model = Task
        fields = ['title', 'description', 'completed']

Step 10: Configure URLs

Set up the URLs for your app. Create a file named urls.py in the tasks directory and add:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.task_list, name='task_list'),
    path('task/new/', views.task_create, name='task_create'),
    path('task/<int:pk>/edit/', views.task_update, name='task_update'),
    path('task/<int:pk>/delete/', views.task_delete, name='task_delete'),
]

Then, include these URLs in your main project’s urls.py file:

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

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

Step 11: Create HTML Templates

Create a folder named templates in the tasks directory, and then create the following HTML files:

  1. task_list.html
  2. task_form.html
  3. task_confirm_delete.html

Here’s a simple example for task_list.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Task List</title>
</head>
<body>
    <h1>Task List</h1>
    <a href="{% url 'task_create' %}">Create New Task</a>
    <ul>
        {% for task in tasks %}
            <li>
                {{ task.title }} - <a href="{% url 'task_update' task.pk %}">Edit</a> - 
                <a href="{% url 'task_delete' task.pk %}">Delete</a>
            </li>
        {% endfor %}
    </ul>
</body>
</html>

Step 12: Run Your Application

Now that everything is set up, run your Django server:

python manage.py runserver

Visit http://127.0.0.1:8000/ in your web browser to see your CRUD application in action!

Conclusion

Congratulations! You have successfully built a simple CRUD application with Django. This foundational knowledge sets the stage for more complex applications and features, such as user authentication, advanced querying, and API integrations. As you continue your journey with Django, keep exploring its robust features to enhance your applications further. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.