Creating a simple CRUD application with Django

Creating a Simple CRUD Application with Django

Introduction

Django, a high-level Python web framework, is designed to encourage rapid development and clean, pragmatic design. One of the essential features of web applications is CRUD operations—Create, Read, Update, and Delete. This article will guide you through the process of building a simple CRUD application using Django, perfect for beginners and seasoned developers alike. By the end of this tutorial, you'll have a functional application and a deeper understanding of Django's capabilities.

What is CRUD?

CRUD stands for:

  • Create: Adding new data to the database.
  • Read: Retrieving and displaying data from the database.
  • Update: Modifying existing data in the database.
  • Delete: Removing data from the database.

CRUD operations are fundamental to almost all web applications, allowing users to manage data effectively. Let’s dive into building a simple CRUD application.

Setting Up Your Django Project

Step 1: Install Django

Before we start coding, you need to have Python and pip installed on your machine. You can install Django using pip. Open your terminal and run:

pip install django

Step 2: Create a New Django Project

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

django-admin startproject mycrudapp
cd mycrudapp

Step 3: Create a New App

In Django, an application is a web application that does something—like handling a blog or a database of records. To create a new app, run:

python manage.py startapp records

Step 4: Configure Your App

Add the new app to your project by including it in the INSTALLED_APPS list in settings.py:

# mycrudapp/settings.py

INSTALLED_APPS = [
    ...
    'records',
]

Defining the Model

A model in Django is a class that defines the fields and behaviors of the data you’re storing. In our CRUD application, we’ll create a simple model for a record.

Step 5: Create a Model

Open models.py in your records app and define a model:

# records/models.py

from django.db import models

class Record(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()

    def __str__(self):
        return self.title

Step 6: Migrate the Database

After defining your model, it’s time to create the database table. First, make migrations and then migrate:

python manage.py makemigrations
python manage.py migrate

Creating Views for CRUD Operations

Step 7: Create Views

Next, we will create views to handle our CRUD operations. Open views.py in your records app and add the following code:

# records/views.py

from django.shortcuts import render, redirect, get_object_or_404
from .models import Record
from .forms import RecordForm

def record_list(request):
    records = Record.objects.all()
    return render(request, 'record_list.html', {'records': records})

def record_create(request):
    if request.method == 'POST':
        form = RecordForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('record_list')
    else:
        form = RecordForm()
    return render(request, 'record_form.html', {'form': form})

def record_update(request, pk):
    record = get_object_or_404(Record, pk=pk)
    if request.method == 'POST':
        form = RecordForm(request.POST, instance=record)
        if form.is_valid():
            form.save()
            return redirect('record_list')
    else:
        form = RecordForm(instance=record)
    return render(request, 'record_form.html', {'form': form})

def record_delete(request, pk):
    record = get_object_or_404(Record, pk=pk)
    if request.method == 'POST':
        record.delete()
        return redirect('record_list')
    return render(request, 'record_confirm_delete.html', {'record': record})

Step 8: Create Forms

To handle user input, create a form class. Create a new file called forms.py in your records app:

# records/forms.py

from django import forms
from .models import Record

class RecordForm(forms.ModelForm):
    class Meta:
        model = Record
        fields = ['title', 'description']

Setting Up URLs

Step 9: Define URLs

You need to connect your views to URLs. Open urls.py in your records app and add:

# records/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.record_list, name='record_list'),
    path('record/new/', views.record_create, name='record_create'),
    path('record/<int:pk>/edit/', views.record_update, name='record_update'),
    path('record/<int:pk>/delete/', views.record_delete, name='record_delete'),
]

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

# mycrudapp/urls.py

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

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

Creating Templates

Step 10: Create HTML Templates

Now, create HTML templates for listing, creating, updating, and confirming deletion of records. Create a folder named templates inside your records directory and add the following files:

  1. record_list.html
  2. record_form.html
  3. record_confirm_delete.html

Here's a simple example for record_list.html:

<!-- records/templates/record_list.html -->

<h1>Record List</h1>
<a href="{% url 'record_create' %}">Create New Record</a>
<ul>
    {% for record in records %}
        <li>
            {{ record.title }} - <a href="{% url 'record_update' record.pk %}">Edit</a>
            <form action="{% url 'record_delete' record.pk %}" method="post" style="display:inline;">
                {% csrf_token %}
                <input type="submit" value="Delete">
            </form>
        </li>
    {% endfor %}
</ul>

Running Your Application

Step 11: Start the Development Server

To see your application in action, start the Django development server:

python manage.py runserver

Open your browser and navigate to http://127.0.0.1:8000/ to view your CRUD application. You can now create, read, update, and delete records!

Conclusion

Congratulations! You’ve successfully built a simple CRUD application using Django. This application serves as a great foundation for more complex projects. By mastering CRUD operations, you can handle data dynamically and efficiently in your web applications.

Next Steps

  • Explore Django’s authentication system to secure your application.
  • Add more complex relationships between models.
  • Implement pagination to handle large datasets better.

By following this guide, you're well on your way to becoming proficient in Django development. 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.