Python Django CRUD Example Tutorial

Published On: 21/06/2022 | Category: Django Python


Hey Friends,

In this quick example, let's see django tutorial & crud example with mysql and bootstrap. step by step explain django crud operations with mysql backend. step by step explain django crud operations with mysql bootstrap. let’s discuss about django crud operations with mysql database.

Here i will give you simple example of django crud operations with mysql database, So let's see the below example:

Step 1 : Installing Django and MySQL Client

First of all In this step, we’ll install django and mysql client from PyPI using pip in our activated virtual environment.

Here next to your command-line interface and run the following command to install the django package:

pip install django

we will also need to install the mysql client for Python using pip:

pip install mysqlclient
Step 2 : Create a Project

In this second step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject crudexample
Step 3 : Create a App
python3 manage.py startapp blog

Next, you need to add it in the settings.py file as follows:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
]
Step 4 : Database Setup

Next step, we will modify the settings.py file and update the database settings to configure the mydb database:

settings.py
DATABASES = {  
    'default': {  
        'ENGINE': 'django.db.backends.mysql',  
        'NAME': 'crudapp',  
        'USER':'root',  
        'PASSWORD':'root',  
        'HOST':'localhost',  
        'PORT':'3306'  
    }  
}  
Step 5 : Create a Model

In this step. we will require the database model for storing contacts.Open the blog/models.py file and add the following code:

blog/models.py
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField()
    created_at = models.DateTimeField( auto_now_add = True)

    class Meta:  
        db_table = "members_posts"

After creating these model, you need to create migrations using the following command:

Step 6 : Create a Migrations
python manage.py makemigrations

After successfully run the above command go to the blog/migrations/0001_initial.py

blog/migrations/0001_initial.py
# Generated by Django 4.0.5 on 2022-06-18 07:03

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='members_posts',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=255)),
                ('description', models.TextField()),
                ('created_at', models.DateTimeField(auto_now_add = True)),
            ],
        ),
    ]

Next, you need to migrate your database using the following command:

python manage.py migrate
Step 7 : Creating the Views

In this step, we need to create the views for performing the CRUD operations.Open the blog/views.py file and add:

blog/views.py
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.urls import reverse
from .models import Post
from django.views.generic import ListView
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

# Listing Page
def index(request):
    posts = Post.objects.all()
    page = request.GET.get('page', 1)

    paginator = Paginator(posts, 3)
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)

    return render(request, 'index.html', { 'posts': posts })

# Create Post
def add(request):
    template = loader.get_template('create.html')
    return HttpResponse(template.render({}, request))

# Store Blog
def addrecord(request):
    x = request.POST['title']
    y = request.POST['description']
    post = Post(title=x, description=y)
    post.save()
    return HttpResponseRedirect(reverse('index'))

# Delete Post
def delete(request, id):
    post = Post.objects.get(id=id)
    post.delete()
    return HttpResponseRedirect(reverse('index'))

# Update Post
def update(request, id):
    post = Post.objects.get(id=id)
    template = loader.get_template('update.html')
    context = {
        'post': post,
    }
    return HttpResponse(template.render(context, request))

# Update Post
def updaterecord(request, id):
    title = request.POST['title']
    description = request.POST['description']
    post = Post.objects.get(id=id)
    post.title = title
    post.description = description
    post.save()
    return HttpResponseRedirect(reverse('index'))

# Show Post
def show(request, id):
    post = Post.objects.get(id=id)
    template = loader.get_template('show.html')
    context = {
        'post': post,
    }
    return HttpResponse(template.render(context, request))
Step 8 : Creating Django Templates

In this step Open the settings.py file and add os.path.join(BASE_DIR, 'templates') to the TEMPLATES array:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        "DIRS": [BASE_DIR / "templates"],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Next will tell django to look for the templates in the templates folder.Next, inside the blog folder create a templates folder:

mkdir templates

Next, inside the templates folder, create the following files:

  • index.html
  • create.html
  • edit.html
  • show.html

Next, open the blog/templates/index.html file and the add:

/blog/templates/index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <div class="row">
                            <div class="col-md-9">
                                <h3>Python Django CRUD Example Tutorial - Tuts-Station.com</h3>
                            </div>
                            <div class="col-md-3 text-right">
                                <a href="add/" class="btn btn-success btn-sm"> <i class="fa fa-plus"></i></a>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <table class="table table-bordered table-hover">
                            <thead>
                                <tr>
                                    <th width="150">Title</th>
                                    <th width="200">Content</th>
                                    <th width="80">Created At</th>
                                    <th width="80">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for post in posts %}
                                    <tr>
                                        <td>{{ post.title }}</td>
                                        <td>{{ post.description }}</td>
                                        <td>{{ post.created_at|date:"M d, Y" }}</td>
                                        <td>
                                            <a href="show/{{ post.id }}" class="btn btn-info btn-sm"> <i class="fa fa-eye"></i></a>
                                            <a href="update/{{ post.id }}" class="btn btn-primary btn-sm"> <i class="fa fa-pencil"></i></a>
                                            <a href="delete/{{ post.id }}" onclick="return confirm('Are you sure you want to delete this?')" class="btn btn-danger btn-sm"> <i class="fa fa-trash"></i></a>
                                        </td>
                                    </tr>
                                    {% empty %}
                                        <tr class="text-center">
                                            <td colspan="4">There are no Record Found!</td>
                                        </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                        <!--Pagination-->
                        <nav aria-label="Page navigation example">
                          <ul class="pagination justify-content-end">
                            {% if posts.has_previous %}
                              <li class="page-item">
                                <a class="page-link" href="?page={{ posts.previous_page_number }}">Previous</a>
                              </li>
                            {% else %}
                              <li class="page-item disabled">
                                <a class="page-link" href="#" tabindex="-1" aria-disabled="True">Previous</a>
                              </li>
                            {% endif %}
                            {% for i in posts.paginator.page_range %}
                              {% if posts.number == i %}
                                <li class="page-item active" aria-current="page">
                                  <span class="page-link">
                                    {{ i }}
                                    <span class="sr-only">(current)</span>
                                  </span>
                                </li>
                              {% else %}
                                <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
                              {% endif %}
                            {% endfor %}
                            {% if posts.has_next %}
                              <li class="page-item">
                                <a class="page-link" href="?page={{ posts.next_page_number }}">Next</a>
                              </li>
                            {% else %}
                              <li class="page-item disabled">
                                <a class="page-link" href="#" tabindex="-1" aria-disabled="True">Next</a>
                              </li>
                            {% endif %}
                          </ul>
                        </nav>
                        <!--end of Pagination-->
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Next, open the blog/templates/create.html file and the add:

/blog/templates/create.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
    <div class="container mt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h4>Create Post</h4>
                    </div>
                    <div class="card-body">
                        <form method="post" action="addrecord/" enctype="multipart/form-data"> 
                            {% csrf_token %}
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                      <label for="usr">Title:</label>
                                      <input type="text" class="form-control" name="title" id="title" required>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label for="usr">Description:</label>
                                        <textarea class="form-control" name="description" rows="3" id="description" required></textarea>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12 text-center">
                                    <button class="btn btn-success" type="submit">Submit</button>
                                    <a class="btn btn-danger" href="{% url 'index' %}" type="button">Cancel</a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Next, open the blog/templates/edit.html file and the add:

/blog/templates/edit.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha512-SfTiTlX6kk+qitfevl/7LibUOeJWlt9rbyDn92a1DqWOw9vWG2MFoays0sgObmWazO5BQPiFucnnEAjpAB+/Sw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
    <div class="container mt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <div class="row">
                            <div class="col-md-12">
                                <h3>Update Post</h3>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <form action="updaterecord/{{ post.id }}" method="post"> 
                            {% csrf_token %}
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                      <label for="usr">Title:</label>
                                      <input type="text" class="form-control" name="title" id="title" value="{{ post.title }}" required>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label for="usr">Description:</label>
                                        <textarea class="form-control" name="description" rows="3" id="description" required>{{ post.description }}</textarea>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12 text-center">
                                    <button class="btn btn-success" type="submit">Update</button>
                                    <a class="btn btn-danger" href="{% url 'index' %}" type="button">Cancel</a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Next, open the blog/templates/show.html file and the add:

/blog/templates/show.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha512-SfTiTlX6kk+qitfevl/7LibUOeJWlt9rbyDn92a1DqWOw9vWG2MFoays0sgObmWazO5BQPiFucnnEAjpAB+/Sw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <div class="row">
                            <div class="col-md-9">
                                <h3>Show</h3>
                            </div>
                            <div class="col-md-3 text-right">
                                <a href="{% url 'index' %}" class="btn btn-success btn-sm"> <i class="fa fa-arrow-left"></i></a>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <table class="table table-bordered table-hover">
                            <tbody>
                                <tr>
                                    <th width="200px">Title</th>
                                    <td>{{ post.title }}</td>
                                </tr>
                                <tr>
                                    <th width="200px">Description</th>
                                    <td>{{ post.description }}</td>
                                </tr>
                                <tr>
                                    <th width="200px">Created At</th>
                                    <td>{{ post.created_at|date:"M d, Y" }}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
Step 9 : Creating URLs

In this section, we’ll create the urls to access our CRUD views.Go to the urls.py blog/urls.py file and update it as follows:

blog/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('add/', views.add, name='add'),
    path('add/addrecord/', views.addrecord, name='addrecord'),
    path('delete/<int:id>', views.delete, name='delete'),
    path('update/<int:id>', views.update, name='update'),
    path('update/updaterecord/<int:id>', views.updaterecord, name='updaterecord'),
    path('show/<int:id>', views.show, name='show'),
]

Next, we will require the modify the urls.py your root preoject folder lets update the file.

crudexample/urls.py
from django.contrib import admin
from django.urls import path, include
    
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls')),
]
Step 10 : Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the http://localhost:8000/ address with a web browser.

I Hope It will help you....