How to create a basic CRUD application in Django

How to Create a Basic CRUD Application in Django

Creating a CRUD (Create, Read, Update, Delete) application is one of the fundamental tasks in web development. It allows you to interact with a database and manage data effectively. Django, a high-level Python web framework, simplifies the process of building web applications by providing a robust structure and numerous built-in features. In this article, we’ll walk through the steps to create a basic CRUD application using Django, complete with code snippets and actionable insights.

What is CRUD?

CRUD stands for Create, Read, Update, and Delete. These are the four basic operations that can be performed on data in a database. In a web application, CRUD functionality allows users to:

  • Create new records (e.g., adding a new user).
  • Read existing records (e.g., viewing user details).
  • Update existing records (e.g., modifying user information).
  • Delete records (e.g., removing a user).

Use Cases for CRUD Applications

CRUD applications are common in various domains, including:

  • Content Management Systems (CMS): Managing articles, blogs, or media files.
  • E-commerce Platforms: Handling products, orders, and customer data.
  • Social Media Applications: Managing user profiles, posts, and comments.

Setting Up Your Django Environment

Before we dive into coding, let’s set up our Django environment.

Step 1: Install Django

If you haven't installed Django yet, you can do so using pip:

pip install django

Step 2: Create a New Project

Create a new Django project by running the following command:

django-admin startproject crud_app

Navigate into your project directory:

cd crud_app

Step 3: Create a New Application

Now, let’s create a new application within our project:

python manage.py startapp users

Building the CRUD Functionality

Step 4: Define Your Model

In the users/models.py file, define a simple User model:

from django.db import models

class User(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()
    age = models.IntegerField()

    def __str__(self):
        return self.name

Step 5: Register the Model in Admin

To manage our User model via the Django admin interface, register it in users/admin.py:

from django.contrib import admin
from .models import User

admin.site.register(User)

Step 6: Create Database Migrations

Next, we need to create migrations for our new model and apply them:

python manage.py makemigrations
python manage.py migrate

Step 7: Create Views for CRUD Operations

In users/views.py, create views to handle CRUD operations:

from django.shortcuts import render, redirect
from .models import User

def user_list(request):
    users = User.objects.all()
    return render(request, 'user_list.html', {'users': users})

def user_create(request):
    if request.method == 'POST':
        name = request.POST['name']
        email = request.POST['email']
        age = request.POST['age']
        User.objects.create(name=name, email=email, age=age)
        return redirect('user_list')
    return render(request, 'user_form.html')

def user_update(request, pk):
    user = User.objects.get(pk=pk)
    if request.method == 'POST':
        user.name = request.POST['name']
        user.email = request.POST['email']
        user.age = request.POST['age']
        user.save()
        return redirect('user_list')
    return render(request, 'user_form.html', {'user': user})

def user_delete(request, pk):
    user = User.objects.get(pk=pk)
    user.delete()
    return redirect('user_list')

Step 8: Set Up URLs

In users/urls.py, create URL patterns for your CRUD operations:

from django.urls import path
from .views import user_list, user_create, user_update, user_delete

urlpatterns = [
    path('', user_list, name='user_list'),
    path('create/', user_create, name='user_create'),
    path('update/<int:pk>/', user_update, name='user_update'),
    path('delete/<int:pk>/', user_delete, name='user_delete'),
]

Make sure to include these URLs in your project’s main urls.py:

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

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

Step 9: Create Templates

Now, create HTML templates to display and manage users. Create a folder named templates inside the users directory and add the following files:

user_list.html

<h1>User List</h1>
<a href="{% url 'user_create' %}">Add User</a>
<ul>
    {% for user in users %}
        <li>
            {{ user.name }} - {{ user.email }} - {{ user.age }}
            <a href="{% url 'user_update' user.pk %}">Edit</a>
            <a href="{% url 'user_delete' user.pk %}">Delete</a>
        </li>
    {% endfor %}
</ul>

user_form.html

<h1>{% if user %}Edit{% else %}Create{% endif %} User</h1>
<form method="post">
    {% csrf_token %}
    <input type="text" name="name" value="{{ user.name|default:'' }}" placeholder="Name" required>
    <input type="email" name="email" value="{{ user.email|default:'' }}" placeholder="Email" required>
    <input type="number" name="age" value="{{ user.age|default:'' }}" placeholder="Age" required>
    <button type="submit">Submit</button>
</form>
<a href="{% url 'user_list' %}">Cancel</a>

Step 10: Run the Development Server

Finally, run the development server to see your CRUD application in action:

python manage.py runserver

Visit http://127.0.0.1:8000/users/ in your web browser, and you should see your user list. You can now create, read, update, and delete users effortlessly.

Troubleshooting Common Issues

  • Migration Issues: If you encounter issues with migrations, ensure that you have defined your models correctly and run makemigrations again.
  • Template Not Found: Ensure that your templates are located in the correct directory and that you have set the TEMPLATES setting in settings.py correctly to look for templates in the app directories.

Conclusion

Creating a CRUD application in Django is straightforward and efficient. This guide provides a comprehensive overview of the steps involved, from setting up your environment to building the application. With Django's powerful features and robust structure, you can easily extend this application to include more complex functionalities and integrate it with other systems. 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.