In this Python Django Tutorial, we will learn Django crud examples with MySQL. And, these are the following topics that we are going to discuss in this tutorial.
- Python Django MySQL CRUD
- Python Django MySQL CRUD project setup
- Python Django MySQL CRUD create url pattern
- Python Django MySQL CRUD create model
- Python Django MySQL CRUD create model form
- Python Django MySQL CRUD view function CREATE
- Python Django MySQL CRUD HTML CREATE
- Python Django MySQL CRUD view function RETRIEVE
- Python Django MySQL CRUD HTML RETRIEVE
- Python Django MySQL CRUD view function UPDATE
- Python Django MySQL CRUD HTML UPDATE
- Python Django MySQL CRUD view function DELETE
- Python Django MySQL CRUD HTML DELETE
- Python Django MySQL CRUD Example
Python Django MySql CRUD
In this section, we’ll learn about CRUD operations.
Django is a web framework that performs CRUD operations and is based on the MVT architecture. CRUD stands for Create, Retrieve, Update, and Delete, and they are the essential processes that any web developer should be familiar with.
And we’ll learn about Django’s CRUD operations which are as follow.
- Create: In a database table, create or add new entries.
- Retrieve: Read, Retrieve or Fetch all or some entries from the table in a database.
- Update: In a database table, update or amend existing entries.
- Delete: In a database table, delete existing records.
Also, check: Login system in Python Django
Python Django MySQL CRUD project setup
In this section, we’ll learn how to set up a Django project to perform CRUD operations with MySQL.
CREATE PROJECT: First, we need to create a Django project. For this, type the following command in the terminal.
django-admin startproject PythonGuides
- Here, we create a Django project named PythonGuides.
CREATE APP: Next, within the project, we will create an app named Blog. And later on this, we’ll perform CRUD operations. Type the following command in the terminal to create an app.
python manage.py startapp Blog
CREATE TEMPLATES: After that, we create the Templates folder in the project root directory. We’ll also create an HTML file in the Templates folder.
We’ll create different templates to perform CRUD operations.
- search.html: To display the fetched data.
- create.html: To add a new blog.
- update.html: To update the existing blog.
- remove.html: To delete a blog entity.
INSTALL APP: Then, in the settings.py file, we must include the Blog app.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Blog'
]
ADD TEMPLATES: We also need to add the Templates directory with our project’s directory. Add below code in the settings.py file.
'DIRS': ['Templates']
DATABASE SETUP: Create a MySQL database called Blog and set it up in the Django project’s settings.py file.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'Blog',
'USER':'root',
'PASSWORD':'',
'HOST':'localhost',
'PORT':'3306'
}
}
Install MySQL client: You will also need to install the MySQL client for Python.
pip install mysqlclient
Read: Python filter not in Django
Python Django MySQL CRUD create url pattern
In this section, we’ll learn to create URL Patterns to perform MySQL CRUD operations.
PROJECT URL: Add the following code in the project’s urls.py.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('Blog.urls')),
]
- We add Blog.urls to PythonGuides urls.py file.
APP URL: Next, we will create URL patterns for each view. Add the following code inside Blog urls.py file.
from django.urls import path
from . import views
urlpatterns = [
path('', views.create_blog, name='create-blog'),
path('search/', views.retrieve_blog, name='retrieve-blog'),
path('update/<int:pk>', views.update_blog, name='update-blog'),
path('delete/<int:pk>', views.delete_blog, name='delete-blog'),
]
Python Django MySQL CRUD create model
In this section, we’ll develop a model to execute CRUD actions.
CREATE MODEL: Add the following code inside the models.py file.
from django.db import models
class Blog(models.Model):
BlogId = models.CharField(max_length=30)
Title = models.CharField(max_length=200)
Author_Name = models.CharField(max_length=300)
Start_Date = models.DateField()
End_Date = models.DateField()
class Meta:
db_table = 'Blog'
- We will create a Blog model with three CharField and two DateField.
- The respective CharFields are BlogId, Title, and Author_Name.
- And, the respective DateField are Start_Date and End_Date.
REGISTER MODEL: Add the following code in the admin.py file.
from django.contrib import admin
from .models import Blog
admin.site.register(Blog)
- We register the Blog model on the admin site.
Read: Outputting Python to HTML Django
Python Django MySQL CRUD create model form
In this section, we’ll develop a model form to perform CRUD operations.
CREATE FORM: Add the following code in the forms.py file.
from django import forms
from django.forms import ModelForm
from .models import Blog
class BlogForm(forms.ModelForm):
class Meta:
model = Blog
fields = "__all__"
- We create a form class BlogForm.
- Then, we use ModelForm to fetch the model fields from Blog model and then by using those fields we create a form.
Python Django MySQL CRUD view function CREATE
In this section, we’ll learn to create a view function to add a Blog.
create_blog VIEW: Add the following code in the views.py file.
from django.shortcuts import render, redirect
from .forms import BlogForm
from .models import Blog
# Add Blog
def create_blog(request):
if request.method == "POST":
form = BlogForm(request.POST)
if form.is_valid():
try:
form.save()
return redirect('search/')
except:
pass
else:
form = BlogForm()
return render(request, 'create.html', {'form':form})
- We define the create_blog function with request parameter by using which user adds their new blog.
- This function redirects the user to the create.html page.
Read Django CRUD example with PostgreSQL
Python Django MySQL CRUD HTML CREATE
In this section, we’ll learn to create an HTML template for adding a new blog.
create HTML: Add the following code in the create.html file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Blog</title>
</head>
<body>
<h2 style="text-align:center"> Create New Blog </h2>
<form method="POST" >
{% csrf_token %}
{{ form.as_p }}
<input type="submit" class="btn btn-success">
</form>
</body>
</html>
- Here, we use the form element to create an HTML form for user input.
- We also add method=POST to the form tag.
- Then, we use {% csrf_token %} to protect our form from cyber-attacks.
- Next, we render Django forms as paragraphs.
Read: Python Django random number
Python Django MySQL CRUD view function RETRIEVE
In this section, we’ll learn to create a view function that shows the list of all blogs added by users.
retrieve_blog VIEW: Add the following code in the views.py file.
from django.shortcuts import render, redirect
from Blog.forms import BlogForm
from Blog.models import Blog
# Search Blog
def retrieve_blog(request):
blogs = Blog.objects.all()
return render(request,'search.html',{'blogs':blogs} )
- We define the retrieve_blog function with request parameter.
- It display all the details of the blogs enter by the users.
- The function redirects the user to the search.html page.
Python Django MySQL CRUD HTML RETRIEVE
In this section, we’ll learn to create an HTML template that shows the list of blogs added by users.
search HTML: Add the following code in the search.html file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search Blog</title>
</head>
<style>
table,
th,
td
{
border: 2px solid;
}
</style>
<body>
<h2 style="text-align:center"> Blog Informationn </h2>
<table align="center" style="margin: 0px auto;">
<thead>
<tr>
<th>Blog ID</th>
<th>Title</th>
<th>Author</th>
<th>Start Date</th>
<th>End Date</th>
<th>Edit Blog</th>
<th>Remove Blog</th>
</tr>
</thead>
<tbody>
{% for blog in blogs %}
<tr>
<td>{{blog.BlogId}}</td>
<td>{{blog.Title}}</td>
<td>{{blog.Author_Name}}</td>
<td>{{blog.Start_Date}}</td>
<td>{{blog.End_Date}}</td>
<td>
<a href="/update/{{blog.pk}}">Update</a>
</td>
<td>
<a href="/delete/{{blog.pk}}">Delete</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
- Here, we create HTML Template that shows the list of all the blogs enter by users in the Table.
- The followings are the header of the table:
- Blog ID: Shows Blog ID.
- Title: Shows Title of the Blog.
- Author: Shows who writes the specific blog.
- Start Date: When author start writing this blog.
- End Date: When author ends this blog.
- It also show the following action buttons:
- Update: To edit specific entry added by the users.
- Delete: To remove specific entry added by the users.
Read: Python Change Django Version
Python Django MySQL CRUD view function UPDATE
In this section, we’ll learn to create a view function that updates the blog added by users.
update_blog VIEW: Add the following code in the views.py file.
from django.shortcuts import render, redirect
from Blog.forms import BlogForm
from Blog.models import Blog
# Update Blog
def update_blog(request,pk):
blogs = Blog.objects.get(id=pk)
form = BlogForm(instance=blogs)
if request.method == 'POST':
form = BlogForm(request.POST, instance=blogs)
if form.is_valid():
form.save()
return redirect('/search')
context = {
'blogs': blogs,
'form': form,
}
return render(request,'update.html',context)
- The update view is similar to create view.
- The only difference is that, here we create update_blog function and we also pass blogs instance to the form.
- We make updates based on the primary key of the blog.
Python Django MySQL CRUD HTML UPDATE
In this section, we’ll learn how to develop an HTML template that updates a specific field that the user added.
update HTML: Add the following code in the update.html file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Update Blog</title>
</head>
<body>
<h2 style="text-align: center; padding-top: 1em; padding-bottom: 1em;">Edit Blog</h2>
<form action="" method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" class="btn btn-success">
</form>
</body>
</html>
- Here, we use the form element to create an HTML form.
- By using this form users can edit any field which they want to.
Read: Python Django vs Pyramid
Python Django MySQL CRUD view function DELETE
In this section, we’ll learn to create a view function that is used to delete the specific entry added by the user.
delete_blog VIEW: Add the following code in the views.py file.
from django.shortcuts import render, redirect
from Blog.forms import BlogForm
from Blog.models import Blog
# Delete Blog
def delete_blog(request, pk):
blogs = Blog.objects.get(id=pk)
if request.method == 'POST':
blogs.delete()
return redirect('/search')
context = {
'blogs': blogs,
}
return render(request, 'remove.html', context)
- We delete the instance from the database when someone clicks on Delete.
Also, check: Simple Contact Form for website in Python Django
Python Django MySQL CRUD HTML DELETE
In this section, we’ll learn how to develop an HTML template that deletes the entry added by the user.
remove HTML: Add the following code in the remove.html file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Delete Blog</title>
</head>
<body>
<form action="" method="POST">
{% csrf_token %}
<br><br>
<div class="alert alert-danger" role="alert">
Are you sure you want to delete "{{ blogs.emp_name }}"?
</div>
<p>
<a href="{% url 'retrieve-blog' %}"><--Return</a>
</p>
<p>
<input class="btn btn-danger" type="submit" value="Confirm">
</p>
</form>
</body>
</html>
- Here, we create an HTML Template that Deletes the specific entry that the user wants to delete.
- And It also confirms once before the Deletion process.
- And, we can also return to the previous page i.e search template when we click on Return Button.
Read: Django get all data from POST request
Python Django MySQL CRUD Example
In this section, we’ll perform Django CRUD Example using MySQL Relational Database Management System.
Firstly, we have to run some commands on the terminal to create the model.
Commands are as follow:
python manage.py makemigrations
python manage.py migrate
Then, we have to run the server, for this type the following command in the terminal.
python manage.py runserver
Start the server and access the form by defining the URL as http://127.0.0.1:8000.
First, enter all the details in the form to create a new blog and click on Submit Button.
Let’s see how its looks in MySQL.
When we click on Submit button, it renders to search HTML template.
We can see that if we want to edit a blog, we can use the Update Button, and if we want to delete a blog, we can use the Delete Button.
Now, see how it looks when we click on the Update button.
Now, we can edit any of the fields.
- Here I edit the End Date field of the form.
- I change the End Date from 2022-03-06 to 2022-03-08.
Now, see what will happen when we click on the Submit button.
Here, we see that the End Date has been updated.
We can see it also updates blog information at MySQL.
Now, see how it looks when we click on the Delete button.
Now, we can see that before deletion it confirms once “Are you sure you want to delete”.
Now, see what will happen if we click on Return.
We can see that it takes us back to blog information.
Now, see what will happen if we click on Confirm.
We can see that it deletes the blog.
We can see it will also delete blogs from the MySQL database.
You may also like to read the following Django tutorials.
- Python Django length filter
- How to setup Django project
- Get URL parameters in Django
- How to create model in Django
- Python Django app upload files
- Python Django form validation
In this Django Tutorial, we have discussed “Python Django CRUD Example (MySQL)” and we have also discussed the following topics in this tutorial.
- Python Django MySQL CRUD
- Python Django MySQL CRUD project setup
- Python Django MySQL CRUD create url pattern
- Python Django MySQL CRUD create model
- Python Django MySQL CRUD create model form
- Python Django MySQL CRUD view function CREATE
- Python Django MySQL CRUD HTML CREATE
- Python Django MySQL CRUD view function RETRIEVE
- Python Django MySQL CRUD HTML RETRIEVE
- Python Django MySQL CRUD view function UPDATE
- Python Django MySQL CRUD HTML UPDATE
- Python Django MySQL CRUD view function DELETE
- Python Django MySQL CRUD HTML DELETE
- Python Django MySQL CRUD Example
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.