How to Build a CRUD Application with Django

 Building a CRUD Application with Django

CRUD stands for Create, Read, Update, Delete — the basic operations of persistent storage. Django, a popular Python web framework, makes building CRUD apps straightforward.


Step 1: Set Up Your Django Project

Install Django:


bash

Copy

Edit

pip install django

Create a new project:


bash

Copy

Edit

django-admin startproject mycrudapp

cd mycrudapp

Create an app inside the project:


bash

Copy

Edit

python manage.py startapp items

Add the app to settings.py:


Open mycrudapp/settings.py and add 'items' to the INSTALLED_APPS list.


python

Copy

Edit

INSTALLED_APPS = [

    # ... other apps ...

    'items',

]

Step 2: Define Your Model

In items/models.py, create a model representing the data entity. For example, a simple Item with a name and description:


python

Copy

Edit

from django.db import models


class Item(models.Model):

    name = models.CharField(max_length=100)

    description = models.TextField(blank=True)


    def __str__(self):

        return self.name

Step 3: Create and Apply Migrations

Run the following commands to create the database tables for your model:


bash

Copy

Edit

python manage.py makemigrations items

python manage.py migrate

Step 4: Create Views for CRUD Operations

In items/views.py, define views to handle:


List all items (Read)


Add a new item (Create)


Edit an existing item (Update)


Delete an item (Delete)


Example:


python

Copy

Edit

from django.shortcuts import render, get_object_or_404, redirect

from .models import Item

from .forms import ItemForm


# List all items

def item_list(request):

    items = Item.objects.all()

    return render(request, 'items/item_list.html', {'items': items})


# Create a new 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})


# Update an existing item

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_list')

    else:

        form = ItemForm(instance=item)

    return render(request, 'items/item_form.html', {'form': form})


# Delete an item

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})

Step 5: Create Forms

Create a form class in items/forms.py to simplify form handling:


python

Copy

Edit

from django import forms

from .models import Item


class ItemForm(forms.ModelForm):

    class Meta:

        model = Item

        fields = ['name', 'description']

Step 6: Define URLs

In items/urls.py, define URL patterns for your views:


python

Copy

Edit

from django.urls import path

from . import views


urlpatterns = [

    path('', views.item_list, name='item_list'),

    path('create/', views.item_create, name='item_create'),

    path('update/<int:pk>/', views.item_update, name='item_update'),

    path('delete/<int:pk>/', views.item_delete, name='item_delete'),

]

Include this in the main project’s urls.py (mycrudapp/urls.py):


python

Copy

Edit

from django.contrib import admin

from django.urls import path, include


urlpatterns = [

    path('admin/', admin.site.urls),

    path('items/', include('items.urls')),

]

Step 7: Create Templates

Make a folder items/templates/items/ and add HTML files:


item_list.html


html

Copy

Edit

<h1>Items</h1>

<a href="{% url 'item_create' %}">Add New Item</a>

<ul>

  {% for item in items %}

    <li>

      {{ item.name }} - <a href="{% url 'item_update' item.pk %}">Edit</a> | 

      <a href="{% url 'item_delete' item.pk %}">Delete</a>

    </li>

  {% endfor %}

</ul>

item_form.html


html

Copy

Edit

<h1>{{ form.instance.pk|yesno:"Edit Item,Add New Item" }}</h1>

<form method="post">

  {% csrf_token %}

  {{ form.as_p }}

  <button type="submit">Save</button>

</form>

<a href="{% url 'item_list' %}">Back to List</a>

item_confirm_delete.html


html

Copy

Edit

<h1>Confirm Delete</h1>

<p>Are you sure you want to delete "{{ item.name }}"?</p>

<form method="post">

  {% csrf_token %}

  <button type="submit">Yes, delete</button>

  <a href="{% url 'item_list' %}">Cancel</a>

</form>

Step 8: Run the Server

Start the development server:


bash

Copy

Edit

python manage.py runserver

Navigate to http://localhost:8000/items/ to see your CRUD app in action!


Summary

Set up Django project and app.


Define a model to represent data.


Create views to handle create, read, update, and delete.


Use Django forms for easy form handling.


Create templates for UI.


Map URLs to views.


Run the server and test your CRUD operations.

Learn Full Stack Python Course in Hyderabad

Read More

Building Secure Backend APIs in Python

Setting Up RESTful APIs with Flask or Django

Flask vs Django for Full Stack Development: A Comparison

How to Use Django Models for Database Management

Visit Our Quality Thought Training in Hyderabad

Get Directions

Comments

Popular posts from this blog

Understanding Snowflake Editions: Standard, Enterprise, Business Critical

Why Data Science Course?

How To Do Medical Coding Course?