Django CRUD Implementation: A Comprehensive Guide

Django May 25, 2023
πŸ’‘
Django is a powerful Python web framework that follows the Model-View-Template (MVT) architectural pattern. It simplifies the process of creating complex web applications by providing reusable components and a clean, efficient, and modular structure. In this article, we will delve into the implementation of CRUD (Create, Read, Update, and Delete) operations using Django, by creating a project named django_crud with structured folders and following naming conventions.

Setting Up the Environment

Before we begin, ensure that you have Python, Django, and a virtual environment installed. You can install Django using the following command:

pip install Django

Create a virtual environment, activate it, and install Django within it:

python -m venv django_crud_env
source django_crud_env/bin/activate
pip install Django

Creating the django_crud Project

To create a new Django project called django_crud, run the following command:

django-admin startproject django_crud
cd django_crud

Create a new Django app named 'products' within the django_crud project:

python manage.py startapp products

The updated structure will look like this:

django_crud/
β”œβ”€β”€ django_crud/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ asgi.py
β”‚   β”œβ”€β”€ settings.py
β”‚   β”œβ”€β”€ urls.py
β”‚   └── wsgi.py
β”œβ”€β”€ products/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ admin.py
β”‚   β”œβ”€β”€ apps.py
β”‚   β”œβ”€β”€ migrations/
β”‚   β”‚   └── __init__.py
β”‚   β”œβ”€β”€ models.py
β”‚   β”œβ”€β”€ tests.py
β”‚   └── views.py
└── manage.py

Naming Conventions

Django promotes the use of meaningful names for the various components of an application. Here are some conventions for our django_crud project:

  • App name: 'products'
  • Model name: 'Product'
  • View names: 'ProductCreateView', 'ProductListView', 'ProductUpdateView', 'ProductDeleteView'
  • Template names: 'product_create.html', 'product_list.html', 'product_update.html', 'product_delete.html'
  • URL names: 'product_create', 'product_list', 'product_update', 'product_delete'

Django Models and Migrations

Create a model named 'Product' in the 'models.py' file within the 'products' app

from django.db import models


class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

Run the following commands to create and apply migrations:

python manage.py makemigrations
python manage.py migrate

Register the 'products' app in the 'INSTALLED_APPS' list in the 'settings.py' file of the django_crud project:

# settings.py
INSTALLED_APPS = [
    # ...
    'products',
]

Register the 'Product' model in the 'admin.py' file of the 'products' app:

# admin.py
from django.contrib import admin
from .models import Product

admin.site.register(Product)

Ensure that you have made migrations for the 'products' app:

python manage.py makemigrations products

You should see output similar to this:

Migrations for 'products':
  products/migrations/0001_initial.py
    - Create model Product

Next, apply the migrations:

python manage.py migrate

The output should resemble:

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, products, sessions
Running migrations:
  Applying products.0001_initial... OK

Now, the 'products_product' table should be created in the database.

Implementing CRUD Views

In the 'views.py' file of the 'products' app, implement the CRUD views using Django's generic views.

Create View

from django.urls import reverse_lazy
from django.views.generic.edit import CreateView
from .models import Product

class ProductCreateView(CreateView):
    model = Product
    fields = ['name', 'price', 'description']
    template_name = 'product_create.html'
    success_url = reverse_lazy('product_list')

Read View

from django.views.generic.list import ListView

class ProductListView(ListView):
    model = Product
    template_name = 'product_list.html'

Update View

from django.views.generic.edit import UpdateView

class ProductUpdateView(UpdateView):
    model = Product
    fields = ['name', 'price', 'description']
    template_name = 'product_update.html'
    success_url = reverse_lazy('product_list')

Delete View

from django.views.generic.edit import DeleteView

class ProductDeleteView(DeleteView):
    model = Product
    template_name = 'product_delete.html'
    success_url = reverse_lazy('product_list')

URL Configuration and Routing

Update the 'urls.py' files in the 'django_crud' project and 'products' app to configure the URL patterns.

Project 'urls.py':

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

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

App 'urls.py':

from django.urls import path
from .views import ProductCreateView, ProductListView, ProductUpdateView, ProductDeleteView

urlpatterns = [
    path('create/', ProductCreateView.as_view(), name='product_create'),
    path('', ProductListView.as_view(), name='product_list'),
    path('<int:pk>/update/', ProductUpdateView.as_view(), name='product_update'),
    path('<int:pk>/delete/', ProductDeleteView.as_view(), name='product_delete'),
]

Creating Templates

To create the templates for each CRUD operation, first create a 'templates' folder within the 'products' app. Then, create the following HTML files: 'product_create.html', 'product_list.html', 'product_update.html', and 'product_delete.html'.

'product_create.html':

{% extends "base.html" %}

{% block content %}
  <h2>Create Product</h2>
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Create</button>
  </form>
{% endblock %}

'product_list.html':

{% extends "base.html" %}

{% block content %}
  <h2>Product List</h2>
  <table>
    <thead>
      <tr>
        <th>Name</th>
        <th>Price</th>
        <th>Description</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      {% for product in object_list %}
        <tr>
          <td>{{ product.name }}</td>
          <td>{{ product.price }}</td>
          <td>{{ product.description }}</td>
          <td>
            <a href="{% url 'product_update' product.pk %}">Edit</a>
            <a href="{% url 'product_delete' product.pk %}">Delete</a>
          </td>
        </tr>
      {% endfor %}
    </tbody>
  </table>
  <a href="{% url 'product_create' %}">Create a new product</a>
{% endblock %}

'product_update.html':

{% extends "base.html" %}

{% block content %}
  <h2>Update Product</h2>
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Update</button>
  </form>
{% endblock %}

'product_delete.html':

{% extends "base.html" %}

{% block content %}
  <h2>Delete Product</h2>
  <p>Are you sure you want to delete "{{ object.name }}"?</p>
  <form method="post">
    {% csrf_token %}
    <button type="submit">Yes, delete</button>
  </form>
  <a href="{% url 'product_list' %}">Cancel</a>
{% endblock %}

Don't forget to create a 'base.html' file in the 'templates' folder, which will be the base template for all other templates:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Django CRUD</title>
</head>
<body>
  <div>
    {% block content %}
    {% endblock %}
  </div>
</body>
</html>

These templates contain the appropriate forms and tables for each CRUD operation. You can customize the appearance and layout by adding CSS and additional HTML elements as needed.

After completing these steps, you should have a fully functional Django CRUD application. To recap, the project should have the following structure:

django_crud/
β”œβ”€β”€ django_crud/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ asgi.py
β”‚   β”œβ”€β”€ settings.py
β”‚   β”œβ”€β”€ urls.py
β”‚   └── wsgi.py
β”œβ”€β”€ products/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ admin.py
β”‚   β”œβ”€β”€ apps.py
β”‚   β”œβ”€β”€ migrations/
β”‚   β”‚   └── __init__.py
β”‚   β”œβ”€β”€ models.py
β”‚   β”œβ”€β”€ templates/
β”‚   β”‚   β”œβ”€β”€ base.html
β”‚   β”‚   β”œβ”€β”€ product_create.html
β”‚   β”‚   β”œβ”€β”€ product_delete.html
β”‚   β”‚   β”œβ”€β”€ product_list.html
β”‚   β”‚   └── product_update.html
β”‚   β”œβ”€β”€ tests.py
β”‚   β”œβ”€β”€ urls.py
β”‚   └── views.py
└── manage.py

Now, you should be able to run the development server, access the admin panel to manage products, and use the CRUD views to create, read, update, and delete products:

python manage.py runserver

Access the application at 'http://127.0.0.1:8000/products/'

In conclusion, this comprehensive guide has provided you with a solid foundation for implementing CRUD operations in Django, using structured folders and following naming conventions. By applying these concepts, you can build robust and scalable web applications.

To access the complete source code for this tutorial, please visit the following GitHub repository:https://github.com/anuragdeepxon/django_crud.git.

Tags

Anurag Deep

Logical by Mind, Creative by Heart