DEV Community

Rhonajoy
Rhonajoy

Posted on • Updated on

What are CRUD Methods? How can we Implement them in Django?

The acronym CRUD stands for CREATE, READ,UPDATE and DELETE. They refer to the four basic functions that can be executed on a set of data. Each of these functions represent a specific HTTP method.

In this article, we are going to create a django project that can create,read,update and delete posts from scratch to demonstrate these four concepts.

How to Implement CRUD Methods in Django
Create virtual environment using
python3 -m venv <name of virtual>

Activate your virtual:(for Ubuntu users):
source <name of your virtual>/bin/activate
For windows Users:
.\venv\Scripts\activate

Install Django :q
pip install django

Create a django project
django-admin startproject <projectname>.

Create a django application
python3 manage.py startapp <appname>

We’ll start by creating our model for our posts
Ensure to have created a database prior and linked it in the settings.py file like so:

DATABASES = {
   'default': {
       'ENGINE': 'django.db.backends.postgresql',
       'NAME': ‘<database name>’,
       'USER': '<database user>',
   'PASSWORD':'<password>',
   }
}
Enter fullscreen mode Exit fullscreen mode

NB if you are using the postgresql database, you need to install psycopg2 i.e (pip install pyscopg2)

from django.db import models

# Create your models here.
class Posts(models.Model):
   name = models.CharField(max_length = 50)
   picture = models.ImageField()
   author = models.CharField(max_length = 30, default="anonymous")
   email = models.EmailField(blank = True)
   describe = models.TextField(default = " Django tutorials")
   def __str__(self):
       return self.name
Enter fullscreen mode Exit fullscreen mode

Make the models known to the database by initializing migrations
python3 manage.py makemigrations
And then make migrations
python3 manage.py migrate

CREATE function.
The CREATE function translates to the POST http method . Through Create we are able to add items into our database/data. In this case, to be able to add posts into our database. We need to provide an interface for our users to add posts, therefore we create a forms.py file in our app and then inside it we create a form that borrows from our models

from django import forms
from .models import Posts
class PostCreate(forms.ModelForm):
   class Meta:
       model=Posts
       fields='__all__'
Enter fullscreen mode Exit fullscreen mode

We now proceed to our views.py to create the logic . Ensure to import the following at the beginning of the views.py file

from django.shortcuts import render, redirect
from .models import Posts
from .forms import PostCreate
from django.http import HttpResponse

def upload(request):
   upload=PostCreate()
   if request.method=='POST':
       upload=PostCreate(request.POST,request.FILES)
       if upload.is_valid():
           upload.save()
           return redirect('index')
       else:
           return HttpResponse("Your form is wrong")

   else:
       return render(request,'upload_form.html',{'upload_form':upload})
Enter fullscreen mode Exit fullscreen mode

In our upload function, we initialize a variable that stores our form and then specify that the method we are targeting is the POST method,reason being we want to send posts to our database. We check if the form is correctly filled,if yes we save the posts in the database. If not we send an error message.
And if the method is not a POST method, we return a blank form.
READ
This translates to the GET HTTP method. It helps us to access all the posts that have been stored in the database so far.
We do this using the objects.all() to query all posts that are in the database.

def index(request):
   posts=Posts.objects.all()
   return render(request,'index.html',{'posts':posts})
Enter fullscreen mode Exit fullscreen mode

UPDATE
This translates to the PUT HTTP method. It helps us to not only access posts that are already stored in the database but also, to be able to edit them and store them again.

def update_post(request,post_id):
   post_id=int(post_id)
   try:
       post_up=Posts.objects.get(id=post_id)
   except Posts.DoesNotExist:
       return redirect('index' )
   post_form=PostCreate(request.POST or None,instance=post_up)
   if post_form.is_valid():
       post_form.save()
       return redirect('index')
   return render(request,'upload_form.html',{'upload_form':post_form})
Enter fullscreen mode Exit fullscreen mode

Since, we want to access a post that is already stored in the database, we have to have a way to reference to that particular post. We will make use of the id field since it is the primary key meaning that all posts have unique ids.
We initialize a variable that is going to be used to store the id of the post that is being referenced to.
Using the try and except, we look up if such an id exists in the database.if no, we redirect user to index function. If yes, we query the form with the data that was in it, we then check if has been correctly filled,if yes we save it and redirect to index function.
DELETE
This equates to the DELETE HTTP request method which translates to getting rid of posts in the database. In terms of logic,it is very similar to the update function since we are going to use the post’s id to reference to the post we want to delete. We use the .delete() method to achieve ths functionality.

def delete_post(request,post_id):
   post_id=int(post_id)
   try:
       post_up=Posts.objects.get(id=post_id)
   except Posts.DoesNotExist:
       return redirect('index')
   post_up.delete()
   return redirect('index')
Enter fullscreen mode Exit fullscreen mode

Output
Create Function
Using our form we add a new post,and we click on submit.

Form for creating a post
Read Function
When we view our home page, we see the post that we created being displayed.

our dog post
Update Function
We will use the edit button on the post to change the description in our post to” Dogs are loyal and beautiful creatures.They make good pets’. Clicking on edit button takes me to the form with all its content.

post with initial contents
Once edited, I click on submit .

updating post
On checking our post on the home page, we see that its contents have changed.

updated post
Delete Function
We will use the delete button to remove this post. On clicking the button,we notice that the post is no longer there.
clear page
Conclusion
The CRUD acronym translates to all the major operations done in relational databases such as
Microsoft SQL Server, Oracle Database, MySQL and IBM DB2. They are used in real life applications like in ecommerce sites, social media websites.In the very simplest of forms CRUD methods are used to maintain students records, employee records.

Top comments (7)

Collapse
 
emmamwas99 profile image
emmamwas99

Awesome article

Collapse
 
rhonajoyke profile image
Rhonajoy

Thank you!

Collapse
 
iamjaydev profile image
iamjaydev

👏🏻👏🏻👏🏻

Collapse
 
monginadiana profile image
monginadiana

Great article 👍

Collapse
 
rhonajoyke profile image
Rhonajoy

Thank you!

Collapse
 
fjones profile image
FJones

WHY ARE WE YELLING?

It's worth noting that in django, you can restrict endpoints/controllers/views (much the same way as with spring) to specific request methods, using the @require_http_methods annotation/decorator.

Collapse
 
rhonajoyke profile image
Rhonajoy

Thank you for that insight!