A Django CRUD application is a web application built using Django that allows users to perform the four essential database operations: Create, Read, Update, and Delete. These operations are typically implemented to manage records in a database through Django’s ORM, views, forms, and templates.
Features of a Django CRUD Application
Create: Add new records using forms.
Read: Display records in a list or detail view.
Update: Edit existing records through forms.
Delete: Remove records with confirmation dialogs.
Components of a Django CRUD Application
1. Models (Database Layer)
Models define the structure of the data, serving as the link between your application and the database.
Example:
from django.db import models
class Item(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
2. Views (Logic Layer)
Views handle the application’s logic and determine what data to send to templates. Django supports:
Function-based Views (FBVs) for simple logic.
Class-based Views (CBVs) like ListView, CreateView, UpdateView, and DeleteView for streamlined CRUD functionality.
Example of CBVs for CRUD:
from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from .models import Item
from django.urls import reverse_lazy
class ItemListView(ListView):
model = Item
template_name = "item_list.html"
class ItemCreateView(CreateView):
model = Item
fields = ['name', 'description', 'price']
template_name = "item_form.html"
class ItemUpdateView(UpdateView):
model = Item
fields = ['name', 'description', 'price']
template_name = "item_form.html"
class ItemDeleteView(DeleteView):
model = Item
success_url = reverse_lazy('item-list')
3. Templates (Presentation Layer)
Templates render the HTML for the application’s user interface.
Example:
<h1>Item List</h1>
<ul>
{% for item in object_list %}
<li>{{ item.name }} - {{ item.price }}</li>
{% endfor %}
</ul>
<a href="{% url 'item-create' %}">Add New Item</a>
4. URLs (Routing)
URL patterns map HTTP requests to specific views.
from django.urls import path
from .views import ItemListView, ItemCreateView, ItemUpdateView, ItemDeleteView
urlpatterns = [
path('', ItemListView.as_view(), name='item-list'),
path('create/', ItemCreateView.as_view(), name='item-create'),
path('/update/', ItemUpdateView.as_view(), name='item-update'),
path('/delete/', ItemDeleteView.as_view(), name='item-delete'),
]
Django CRUD Application – Objective Questions (MCQs)
Q1. A CRUD application mainly works with:
Q2. To display records in CRUD, which ORM method is used?
Q3. Which method is used to update existing records?
Q4. Which ORM method deletes records?
Q5. In CRUD app, forms are used to: