How to create a simple CRUD application in Django

How to Create a Simple CRUD Application in Django

Creating a CRUD (Create, Read, Update, Delete) application is a fundamental task for any web developer. It allows you to manage data effectively and serves as a foundation for more complex applications. In this article, we'll walk through the process of building a simple CRUD application using Django, a powerful web framework that simplifies web development through its built-in features.

What is CRUD?

CRUD stands for: - Create: Add new records to the database. - Read: Retrieve and display existing records. - Update: Modify existing records. - Delete: Remove records from the database.

CRUD applications are essential for any application that requires data management, such as blog platforms, inventory systems, or user management systems.

Setting Up Your Django Environment

Before diving into the code, ensure you have Django installed. You can install it using pip:

pip install django

Once installed, create a new Django project:

django-admin startproject mycrudapp
cd mycrudapp

Next, create a new Django app where our CRUD functionality will reside:

python manage.py startapp items

Defining Your Models

Models in Django are Python classes that define the structure of your database. In your items/models.py file, define a simple model for our CRUD application:

from django.db import models

class Item(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

Running Migrations

After defining your model, you need to create the database table. Run the following commands:

python manage.py makemigrations
python manage.py migrate

Creating Views

Next, we will create views for each CRUD operation. Open items/views.py and add the following code:

from django.shortcuts import render, redirect, get_object_or_404
from .models import Item
from .forms import ItemForm

def item_list(request):
    items = Item.objects.all()
    return render(request, 'items/item_list.html', {'items': items})

def item_detail(request, pk):
    item = get_object_or_404(Item, pk=pk)
    return render(request, 'items/item_detail.html', {'item': item})

def item_create(request):
    if request.method == "POST":
        form = ItemForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('item_list')
    else:
        form = ItemForm()
    return render(request, 'items/item_form.html', {'form': form})

def item_update(request, pk):
    item = get_object_or_404(Item, pk=pk)
    if request.method == "POST":
        form = ItemForm(request.POST, instance=item)
        if form.is_valid():
            form.save()
            return redirect('item_detail', pk=item.pk)
    else:
        form = ItemForm(instance=item)
    return render(request, 'items/item_form.html', {'form': form})

def item_delete(request, pk):
    item = get_object_or_404(Item, pk=pk)
    if request.method == "POST":
        item.delete()
        return redirect('item_list')
    return render(request, 'items/item_confirm_delete.html', {'item': item})

Creating Forms

Django provides a powerful form framework for handling data. Create a new file items/forms.py and add the following code:

from django import forms
from .models import Item

class ItemForm(forms.ModelForm):
    class Meta:
        model = Item
        fields = ['name', 'description']

Setting Up URLs

Next, we need to set up the URLs for our CRUD operations. Open items/urls.py (create this file if it doesn't exist) and add:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.item_list, name='item_list'),
    path('item/<int:pk>/', views.item_detail, name='item_detail'),
    path('item/new/', views.item_create, name='item_create'),
    path('item/<int:pk>/edit/', views.item_update, name='item_update'),
    path('item/<int:pk>/delete/', views.item_delete, name='item_delete'),
]

Next, include the app URLs in your main project urls.py:

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

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

Creating Templates

Templates are essential for rendering your data to the user. Create a folder named templates inside your items app, and then create another folder named items. Inside this folder, create the following HTML files:

item_list.html

<h1>Item List</h1>
<a href="{% url 'item_create' %}">Create New Item</a>
<ul>
    {% for item in items %}
        <li>
            <a href="{% url 'item_detail' item.pk %}">{{ item.name }}</a> |
            <a href="{% url 'item_update' item.pk %}">Edit</a> |
            <a href="{% url 'item_delete' item.pk %}">Delete</a>
        </li>
    {% endfor %}
</ul>

item_detail.html

<h1>{{ item.name }}</h1>
<p>{{ item.description }}</p>
<a href="{% url 'item_update' item.pk %}">Edit</a>
<a href="{% url 'item_delete' item.pk %}">Delete</a>
<a href="{% url 'item_list' %}">Back to list</a>

item_form.html

<h1>{% if form.instance.pk %}Edit Item{% else %}New Item{% endif %}</h1>
<form method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Save</button>
</form>
<a href="{% url 'item_list' %}">Cancel</a>

item_confirm_delete.html

<h1>Delete {{ item.name }}?</h1>
<form method="POST">
    {% csrf_token %}
    <button type="submit">Confirm</button>
</form>
<a href="{% url 'item_list' %}">Cancel</a>

Running Your Application

Now that everything is set up, start the Django development server:

python manage.py runserver

Visit http://127.0.0.1:8000/items/ in your browser to see your CRUD application in action. You can create, read, update, and delete items seamlessly.

Conclusion

Creating a simple CRUD application in Django is straightforward and serves as an excellent introduction to web development. By following this guide, you’ve learned how to set up a Django project, define models, create views, and design templates.

As you advance, consider adding features like user authentication, pagination, or API endpoints to expand your application’s functionality. With Django’s rich ecosystem and community support, the possibilities are endless. 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.