Key takeaways:
Django is a Python web framework that follows the MVT (model view template) architecture and simplifies CRUD operations.
The Create operation involves defining a model, running migrations, and creating views to add new records to the database.
The Read operation retrieves data from the database and displays it using views and templates.
The Update operation allows modification of existing records by creating views to handle form submissions and updates.
The Delete operation involves permanently removing records from the database with views and confirmation templates.
Implementing CRUD in Django is straightforward but may require additional security and authentication features in real-world scenarios.
Django is a widely-used Python web framework that enables rapid and straightforward web app development without the installation or dependency issues common in other frameworks. Its architecture follows the MVT (model view template) pattern, making it simple to perform CRUD (create, read, update, delete) operations. These operations are crucial when working with databases and building online applications.
Here’s a detailed guide on how to execute CRUD operations:
In the Create operation, we make a new entry in the database. Follow these steps to add new records to the database:
Define a model: Create a model class in the Django application file, and each attribute of this class will behave as a database field.
# models.pyfrom django.db import modelsclass Student(models.Model):name = models.CharField(max_length=100)email = models.EmailField(unique=True)cgpa = models.DecimalField(max_digits=4, decimal_places=2)def __str__(self):return self.name
Run migrations: Run the following command to make a database table.
Python manage.py makemigrationsPython manage.py migrate
Define a view: Create a view in which queries are made to create desired data in the database.
# Create viewdef student_create(request):if request.method == 'POST':form = StudentForm(request.POST)if form.is_valid():form.save()return redirect('student_list')else:form = StudentForm()return render(request, 'students/student_form.html', {'form': form})
The Read operation allows to read or retrieve data from the tables in the database. Follow these steps to read records from the database:
Define a view: Create a view in which queries are made to retrieve desired data from the database.
from django.shortcuts import render# Create your views here.from django.shortcuts import render, redirect, get_object_or_404from .models import Studentfrom .forms import StudentForm# List viewdef student_list(request):students = Student.objects.all()return render(request, 'students/student_list.html', {'students': students})
Make a template: Make an HTML template to display the retrieved list.
<!DOCTYPE html><html><head><title>Student List</title></head><body><h1>Student List</h1><a href="{% url 'student_create' %}">Add Student</a><table border="1"><tr><th>Name</th><th>Email</th><th>CGPA</th><th>Actions</th></tr>{% for student in students %}<tr><td>{{ student.name }}</td><td>{{ student.email }}</td><td>{{ student.cgpa }}</td><td><a href="{% url 'student_update' student.id %}">Update</a><a href="{% url 'student_delete' student.id %}">Delete</a></td></tr>{% endfor %}</table></body></html>
The update operation is used to make modifications to the database. Follow these steps to update records in the database:
Define a view: Make a view that retrieves the record that needs to be modified, then makes a form with its data and handles form submissions.
# views.pydef student_update(request, id):student = get_object_or_404(Student, id=id)if request.method == 'POST':form = StudentForm(request.POST, instance=student)if form.is_valid():form.save()return redirect('student_list')else:form = StudentForm(instance=student)return render(request, 'students/student_form.html', {'form': form})
Make a template: Make an HTML template to update the retrieved record.
<!DOCTYPE html><html><head><title>Add/Update Student</title></head><body><h1>{% if form.instance.pk %}Update{% else %}Add{% endif %} Student</h1><form method="POST">{% csrf_token %}{{ form.as_p }}<button type="submit">Save</button></form><a href="{% url 'student_list' %}">Back to Student List</a></body></html>
The Delete operation is used to delete an entity from the database permanently. Follow these steps to delete the record from the database:
Define a view: Make a view that retrieves the record to be deleted and then manages the deletion process.
# views.py# Delete viewdef student_delete(request, id):student = get_object_or_404(Student, id=id)if request.method == 'POST':student.delete()return redirect('student_list')return render(request, 'students/student_confirm_delete.html', {'student': student})
Make a template: Make an HTML template to confirm the deletion process.
<!DOCTYPE html><html><head><title>Delete Student</title></head><body><h1>Are you sure you want to delete {{ student.name }}?</h1><form method="POST">{% csrf_token %}<button type="submit">Confirm Delete</button></form><a href="{% url 'student_list' %}">Cancel</a></body></html>
Note: These are easy example code to understand the CRUD process in Django. A real-world application may require more complicated scenarios, security mechanisms, and user authentication.
We've set CRUD operations in simple django application. Press the "Run" button and then click on the link in the below widget to perform CRUD operations.
SQLite format 3 @ $ "