Introduction
CRUD is the abbreviation used for four major operations performed on a datacenter. These operations usually include the following,
- Create
- Read
- Update
- Delete
Every programmer has to deal with these operations at some point. For example, you are developing a social networking website you need to provide the users with a way to create their account and read their profile related data. What if they forgot their user name or password? So you surely need to let them update it. Last but not least they don’t want to be active on your site anymore so delete option is required as you surely wouldn’t want your database to be full of inactive users' records. Not only social networking but most probably you would need to implement these operations in all of your websites, to some point, at some level.
Let’s make our lives easy and talk about it in this article; the 7th in my Django series. I’m assuming that by far you have a pretty good understanding of the Django application. If you have any confusion then refer to the previous articles of the series here.
If you’re wondering why we don't perform the CRUD operations using the admin panel; about which we have talked about earlier in the previous articles; that’s the hardcoded way and is only possible while building. Once you have deployed your site, users will not appear on your doorstep to request an account or update a password. You need to provide users a way to do all that for themselves.
Another way could be by using simple forms but it's a tedious and repetitive part of the job of a developer. You would have to implement a lot of validations; even prefilled fields and so on. It sounds like a nightmare to me not to mention it is an old-fashioned traditional way of doing things. Let’s see what Django has for us in the house.
CRUD using Function-Based Views
Django cares about its ease of use and so is there to help us with its simplified implementation for CRUD operations using Function-Based views. These views are easy to read and pretty straightforward. A simple example will help us better understand it.
Let’s say we want to make our site a platform where a user can add their favorite movies. Nothing complex, we’ll just let a user add, edit and delete the movies. Let’s get started.
Create a new project by executing the following command.
- django-admin startproject CRUD
- # CRUD is the name of project
And execute the following command to start app name CRUD_FBVs.
- python manage.py startapp CRUD_FBVs
Don’t forget to add your new app to the Installed app. Append CRUD/settings.py as follow,
- INSTALLED_APPS = [
- 'django.contrib.admin',
- 'django.contrib.auth',
- 'django.contrib.contenttypes',
- 'django.contrib.sessions',
- 'django.contrib.messages',
- 'django.contrib.staticfiles',
- 'CRUD_FBVs',
- ]
Let’s start by creating our movie model. Open CRUD_FBVs/models.py and add the following code to it.
- from django.db import models
- from django.urls import reverse
- from django.contrib.auth.models import User
- class Movies(models.Model):
- '''''by specifying user as Foreign Key, we're using the builtin User model of django.'''
- user = models.ForeignKey(User, on_delete=models.CASCADE)
- title = models.CharField(max_length=200)
- genre = models.CharField(max_length=200)
- def __unicode__(self):
- return self.title
- def get_absolute_url(self):
- return reverse('CRUD_FBVs:movies_edit', kwargs={'pk': self.pk})
We simply defined the model Movies by defining two fields, title and genre. We also defined the user as the Foreign Key so that we’ll be able to use the built-in user model. By defining __unicode__() method, Django will call it when it needs to render an object in a context where a string representation is needed. get_absolute_url() method will tell Django how to calculate the canonical URL for an object. In other words, this method will return a string that can be used to refer to the object over HTTP.
Now apply the migrations as follows:
- python manage.py makemigrations
and
- python manage.py migrate
Let’s register our model to the admin interface. Modify CRUD_FBVs/admin.py file as follow,
- from django.contrib import admin
- from .models import Movies
- admin.site.register(Movies)
We also need to create a simple form to perform CRUD operations. Create a new python file inside your app and name it forms.py. Append the following code to it.
- from django import forms
- from .models import Movies
- class MoviesForm(forms.ModelForm):
- class Meta:
- model = Movies
- fields = ['title', 'genre']
Function Based views uses decorators to achieve the special functionality. Let’s see how that works. Edit views.py file as follow:
- from django.contrib.auth.decorators import login_required
- from django.shortcuts import render, get_object_or_404, redirect
- from .forms import MoviesForm
- from CRUD_FBVs.models import Movies
- @login_required
- def movies_list(request):
- if request.user.is_superuser:
- movies = Movies.objects.all()
- else:
- movies = Movies.objects.filter(user=request.user)
- return render(request, 'movies_list.html', {
- 'object_list': movies
- })
- @login_required
- def movies_create(request):
- form = MoviesForm(request.POST or None)
- if form.is_valid():
- movies = form.save(commit=False)
- movies.user = request.user
- movies.save()
- return redirect('CRUD_FBVs:movies_list')
- return render(request, 'movies_form.html', {'form': form})
- @login_required
- def movies_update(request, pk):
- if request.user.is_superuser:
- movies = get_object_or_404(Movies, pk=pk)
- else:
- movies = get_object_or_404(Movies, pk=pk, user=request.user)
- form = MoviesForm(request.POST or None, instance=movies)
- if form.is_valid():
- form.save()
- return redirect('CRUD_FBVs:movies_list')
- return render(request, 'movies_form.html', {'form': form})
- @login_required
- def movies_delete(request, pk):
- if request.user.is_superuser:
- movies = get_object_or_404(Movies, pk=pk)
- else:
- movies = get_object_or_404(Movies, pk=pk, user=request.user)
- if request.method == 'POST':
- movies.delete()
- return redirect('CRUD_FBVs:movies_list')
- return render(request, 'confirm_delete.html', {'object': movies})

Raichand RayPosted Oct 29, 2020, 5:42 AM
Hi, Look at this new Django CRUD Tutorial https://www.c-sharpcorner.com/article/django-crud-createretriveupdatedelete-record-using-django-class-based-view2/
hendi santikaPosted Feb 7, 2019, 4:55 PM
Nice article & nice example. How to run the CBV app?