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

How to Create a CRUD Application with Django

Creating a CRUD (Create, Read, Update, Delete) application is a fundamental exercise for any developer looking to master web development frameworks. Django, with its powerful features and ease of use, is an excellent choice for building such applications. In this article, we’ll walk you through the process of creating a simple CRUD application using Django, covering everything from setup to deployment.

What is a CRUD Application?

A CRUD application allows users to create, read, update, and delete data. This functionality is essential for nearly all web applications. Here are common use cases:

  • Blog Platforms: Users can create posts, read them, edit their content, and delete them as needed.
  • Inventory Management Systems: Track products, add new items, update existing stock, and remove discontinued products.
  • User Profiles: Create and manage user accounts, allowing users to update their information or delete their profiles.

Setting Up Your Django Environment

Before we dive into the code, let’s ensure you have everything set up correctly.

Prerequisites

  • Python installed (preferably version 3.6 or higher)
  • Django installed (use pip install django)
  • Basic understanding of Python programming

Creating a Django Project

  1. Create a new project: Open your terminal and run: bash django-admin startproject mycrudapp cd mycrudapp

  2. Create a new application: Run the following command to create a new application within your project: bash python manage.py startapp tasks

Updating Settings

Add your newly created app to your project's settings. Open mycrudapp/settings.py and add 'tasks' to the INSTALLED_APPS list:

INSTALLED_APPS = [
    ...
    'tasks',
]

Building the CRUD Functionality

Step 1: Creating the Model

Inside your tasks app, open models.py and define a simple model. For this example, we will create a Task model.

from django.db import models

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

    def __str__(self):
        return self.title

Step 2: Migrating the Database

Now that we have defined our model, we need to create the database tables.

  1. Run the following command to create migrations for your model: bash python manage.py makemigrations

  2. Apply the migrations: bash python manage.py migrate

Step 3: Creating a Basic CRUD Interface

Next, we will set up views and URLs for our CRUD operations.

Setting Up URLs

In the tasks directory, create a new file called urls.py and add the following code:

from django.urls import path
from . import views

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

Now, include these URLs in your main urls.py file (mycrudapp/urls.py):

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

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

Creating Views

In tasks/views.py, create the views for each CRUD operation:

from django.shortcuts import render, get_object_or_404, redirect
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_detail(request, pk):
    task = get_object_or_404(Task, pk=pk)
    return render(request, 'tasks/task_detail.html', {'task': task})

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_edit(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 4: Creating Forms

Create a new file forms.py in the tasks directory and define a form for the Task model:

from django import forms
from .models import Task

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

Step 5: Creating Templates

Create a templates/tasks directory and add the following HTML templates:

  • task_list.html
  • task_detail.html
  • task_form.html
  • task_confirm_delete.html

Here’s a simple example for task_list.html:

<h1>Task List</h1>
<a href="{% url 'task_create' %}">Add New Task</a>
<ul>
    {% for task in tasks %}
        <li>
            <a href="{% url 'task_detail' task.pk %}">{{ task.title }}</a>
            <a href="{% url 'task_edit' task.pk %}">Edit</a>
            <a href="{% url 'task_delete' task.pk %}">Delete</a>
        </li>
    {% endfor %}
</ul>

Step 6: Running Your Application

Now that everything is set up, you can run your Django application:

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’ve successfully created a basic CRUD application using Django. This application provides a foundation for more complex functionalities, such as user authentication and API integrations. As you continue to learn, consider exploring Django REST Framework for building RESTful APIs or customizing your application with advanced features.

Troubleshooting Tips

  • Model Not Found: If you encounter issues related to your model, ensure that you’ve migrated your database correctly.
  • Template Errors: Check that your templates are in the right directory and that the paths are correctly referenced in your views.

By mastering CRUD operations in Django, you’re well on your way to becoming a proficient Django developer. 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.