Django CRUD
Django, a high-level Python web framework, simplifies the creation of web applications with its robust tools for handling CRUD (Create, Read, Update, Delete) operations. This guide walks through implementing CRUD functionality in Django and highlights open-source Django CRUD projects for inspiration.
1. Setting Up a Django Project
Install Django:
bash
pip install django
Start a New Django Project:
bash
django-admin startproject myproject
cd myproject
Create an App:
bash
python manage.py startapp myapp
Add the App to INSTALLED_APPS in settings.py:
INSTALLED_APPS = [
...
'myapp',
]
2. Django CRUD operations
Django makes building CRUD apps seamless with its built-in ORM. Models define database structures, while Django’s views and forms handle data manipulation efficiently.
Model Setup
Define a model representing your database table:
from django.db import models
class User(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(unique=True)
active = models.BooleanField(default=True)
def __str__(self):
return self.name
Run migrations to create the database table:
bash
python manage.py makemigrations
python manage.py migrate
Create (POST)
In Django, creating data involves handling HTTP POST requests and saving data to the database using the model's save() method.
Example: View
from django.shortcuts import render, redirect
from .models import User
def create_user(request):
if request.method == 'POST':
name = request.POST['name']
email = request.POST['email']
user = User(name=name, email=email)
user.save()
return redirect('user_list')
return render(request, 'create_user.html')
Example: Template (create_user.html)
<form method="post">
{% csrf_token %}
<input type="text" name="name" placeholder="Name" required>
<input type="email" name="email" placeholder="Email" required>
<button type="submit">Create</button>
</form>
Read (GET)
The Read operation retrieves data from the database using Django's ORM and renders it to the template.
Example: View
from django.shortcuts import render
def user_list(request):
users = User.objects.all()
return render(request, 'user_list.html', {'users': users})
Example: Template (user_list.html)
<table>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
{% for user in users %}
<tr>
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
</tr>
{% endfor %}
</table>
Update (PUT/PATCH)
Updating data involves fetching a specific object, modifying its fields, and saving the changes.
Example: View
def update_user(request, pk):
user = User.objects.get(id=pk)
if request.method == 'POST':
user.name = request.POST['name']
user.email = request.POST['email']
user.save()
return redirect('user_list')
return render(request, 'update_user.html', {'user': user})
Example: Template (update_user.html)
<form method="post">
{% csrf_token %}
<input type="text" name="name" value="{{ user.name }}" required>
<input type="email" name="email" value="{{ user.email }}" required>
<button type="submit">Update</button>
</form>
Delete (DELETE)
Deleting data involves identifying a specific object and removing it from the database.
Example: View
<form method="post">
{% csrf_token %}
<input type="text" name="name" value="{{ user.name }}" required>
<input type="email" name="email" value="{{ user.email }}" required>
<button type="submit">Update</button>
</form>
Example: Template (delete_user.html)
<p>Are you sure you want to delete {{ user.name }}?</p>
<form method="post">
{% csrf_token %}
<button type="submit">Yes</button>
</form>
Notable libraries and example projects
- Django Ninja CRUD - CRUD example using Django Ninja framework
- Django CRUD with Ajax - CRUD operations with login, registration, and file upload using Ajax in Django
- Django Cruds AdminLTE - AdminLTE-based CRUD generator for Django projects