Python Django CRUD 示例教程

在这个快速示例中,让我们看一下使用 mysql 和 bootstrap 的 django 教程和 crud 示例。逐步解释 django crud 使用 mysql 后端的操作。使用 mysql bootstrap 逐步解释 django crud 操作。让我们讨论一下 django crud 对 mysql 数据库的操作。

在这里,我将给你一个简单的 django crud 操作与 mysql 数据库的例子,让我们看看下面的例子:第 1 步:安装 Django 和 MySQL 客户端

首先在这一步中,我们将在我们激活的虚拟环境中使用 pip 从 PyPI 安装 django 和 mysql 客户端。

在您的命令行界面旁边并运行以下命令来安装 django 包:

pip install django

我们还需要使用 pip 为 Python 安装 mysql 客户端:

pip install mysqlclient

第 2 步:创建项目

在第二步中,我们将使用 django-admin 创建一个新的 django 项目。返回命令行界面并运行以下命令:

django-admin startproject crudexample

第 3 步:创建应用程序

python3 manage.py startapp blog

接下来需要在settings.py文件中添加如下:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
]

第 4 步:数据库设置

下一步,我们将修改 settings.py 文件并更新数据库设置以配置 mydb 数据库:设置.py

DATABASES = {  
    'default': {  
        'ENGINE': 'django.db.backends.mysql',  
        'NAME': 'crudapp',  
        'USER':'root',  
        'PASSWORD':'root',  
        'HOST':'localhost',  
        'PORT':'3306'  
    }  
} 

第 5 步:创建模型

在这一步。我们将需要用于存储联系人的数据库模型。打开 blog/models.py 文件并添加以下代码:博客/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"

创建这些模型后,您需要使用以下命令创建迁移:第 6 步:创建迁移

python manage.py makemigrations

成功运行上述命令后,进入 blog/migrations/0001_initial.py博客/迁移/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)),
            ],
        ),
    ]

接下来,您需要使用以下命令迁移数据库:

python manage.py migrate

第 7 步:创建视图

在这一步中,我们需要创建视图来执行 CRUD 操作。打开 blog/views.py 文件并添加:博客/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))

第 8 步:创建 Django 模板

在这一步中打开 settings.py 文件并将 os.path.join(BASE_DIR, ‘templates’) 添加到 TEMPLATES 数组中:

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',
            ],
        },
    },
]

接下来将告诉 django 在模板文件夹中查找模板。接下来,在blog文件夹中创建一个模板文件夹:

mkdir templates

接下来,在模板文件夹中,创建以下文件:

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

接下来,打开 blog/templates/index.html 文件并添加:/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/bootstrap@4.6.1/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/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>

接下来,打开 blog/templates/create.html 文件并添加:/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/bootstrap@4.6.1/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/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>

接下来,打开 blog/templates/edit.html 文件并添加:/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/bootstrap@4.6.1/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/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>

接下来,打开 blog/templates/show.html 文件并添加:/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/bootstrap@4.6.1/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/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>

第 9 步:创建 URL

在本节中,我们将创建 url 来访问我们的 CRUD 视图。转到 urls.py blog/urls.py 文件并按如下方式更新它:博客/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'),
]

接下来,我们将要求修改您的根 preoject 文件夹的 urls.py 以更新文件。crudexample/urls.py

from django.contrib import admin
from django.urls import path, include
    
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls')),
]

第 10 步:运行服务器

在这一步中,我们将运行本地开发服务器来玩我们的应用程序,而无需将其部署到网络上。

python manage.py runserver

接下来,使用 Web 浏览器访问 http://localhost:8000/ 地址。

我希望它会帮助你……

发表评论

邮箱地址不会被公开。 必填项已用*标注