• Django对数据库进行增加以及查询显示功能实现


    Django对数据库进行增加以及查询显示功能实现



    准备

    1.创建Django框架
    2.安装Django服务与mysqlclient服务
    3.创建子应用
    4.开启数据库服务,并创建一个接下来需要用的新数据库
    (详细内容请见前几章节Django创建第一个应用程序
    Django连接数据库)


    一、初始化应用层下的代码

    1.settings.py

    主要配置INSTALLED_APPS 和DATABASES 数据库服务

    """
    Django settings for 增查 project.
    
    Generated by 'django-admin startproject' using Django 3.1.7.
    
    For more information on this file, see
    https://docs.djangoproject.com/en/3.1/topics/settings/
    
    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/3.1/ref/settings/
    """
    
    from pathlib import Path
    
    # Build paths inside the project like this: BASE_DIR / 'subdir'.
    BASE_DIR = Path(__file__).resolve().parent.parent
    
    
    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
    
    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = 'it38^ojb01ua^x%o8je*(!8udch8r!!!@p74^ra%3%(8jhq2%y'
    
    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True
    
    ALLOWED_HOSTS = []
    
    
    # Application definition
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'stu'
    ]
    
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]
    
    ROOT_URLCONF = '增查.urls'
    
    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',
                ],
            },
        },
    ]
    
    WSGI_APPLICATION = '增查.wsgi.application'
    
    
    # Database
    # https://docs.djangoproject.com/en/3.1/ref/settings/#databases
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'student',# 你自己的数据库名
            'USER': 'root',# 用户名
            'PASSWORD': 'root',# 密码
            'HOST': 'localhost',# 本地ip
            'PORT': 3306,# 端口号
        }
    }
    
    
    # Password validation
    # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
    
    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]
    
    
    # Internationalization
    # https://docs.djangoproject.com/en/3.1/topics/i18n/
    
    LANGUAGE_CODE = 'en-us'
    
    TIME_ZONE = 'UTC'
    
    USE_I18N = True
    
    USE_L10N = True
    
    USE_TZ = True
    
    
    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/3.1/howto/static-files/
    
    STATIC_URL = '/static/'
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127

    2.urls.py

    from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('stu/', include('stu.urls')),# 子应用
    ]
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    3.注意

    以上几步有哪里不懂的小伙伴可以看一下Django创建第一个应用程序
    Django连接数据库

    二、子应用层

    1.urls.py

    from django.urls import path
    
    from stu import views
    
    urlpatterns = [
        path('login/', views.login),
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    2.views.py

    不懂的小伙伴可以观看注释内的文字内容

    from django.http import HttpResponse
    from django.shortcuts import render
    
    from stu.models import Student
    
    
    def login(request):
        # 判断请求方式
        if (request.method == 'GET'):
            # 如果是get请求直接返回页面
            return render(request, 'login.html')
        else:
            # 如果是post请求做表单验证
            sname = request.POST.get('sname')
            spwd = request.POST.get('spwd')
            # sigt是获取注册按钮,前端点击注册按钮就有返回值,没有点击就为空
            sigt=request.POST.get('sigt')
            # 获取数据库表中所有元素.相当于sql语句:select * from student
            stus = Student.objects.all()
            # 先判断是不是注册按钮
            if(sigt != None):
                # 是注册按钮就直接写入数据库
                Student(sname=sname, spwd=spwd).save()
                return HttpResponse('<h1>已为您注册成功!</h1>')
            # 如果是登录按钮,就遍历数据库表中的内容
            for i in stus:
                if (i.sname == sname and i.spwd == spwd):
                    return render(request, 'index.html', {'stus': stus})
            else:
                return HttpResponse('<h1>请先注册!!</h1>')
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    3.models.py

    from django.db import models
    
    class Student(models.Model):
    	# 这里是模型类,这里跟数据库列名要保持一致
        sname=models.CharField(max_length=10)
        spwd=models.CharField(max_length=10)
        class Meta:
            db_table='stu'
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    三.templates中html页面

    1.login.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <form action="/stu/login/" method="post">
            {% csrf_token %}
            用户名:<input type="text" name="sname"><br/>&emsp;码:<input type="password" name="spwd"><br/>
            <input type="submit" value="登录">&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;
            <input type="submit" value="注册" name="sigt">
        </form>
    
    </body>
    </html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    2.index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <table border="1" cellspacing="1" cellpadding="1" width="300px">
            <tr>
                <th>编号</th>
                <th>用户名</th>
                <th>密码</th>
            </tr>
    {#        Django框架可以在html页面中直接写Python代码,使用方式为{% 代码 %}#}
            {% for i in stus %}
                <tr>
    {#                在页面中使用Python代码输出变量#}
                    <td>{{ i.id }}</td>
                    <td>{{ i.sname }}</td>
                    <td>{{ i.spwd }}</td>
                </tr>
            {% endfor %}
        </table>
    
    </body>
    </html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    3.模板语法

    模板语法:
    {%%}
    循环:
    {% for 变量 in 序列 %}
    {% endfor %}
    注释:
    {# #}
    判断:
    {% if: %}
    {% elif: %}
    {% endif %}
    模板变量:
    {{}}

    四.生成迁移文件与执行迁移文件

    生成迁移文件: python manage.py makemigrations
    执行迁移文件: python manage.py migrate stu


    五.执行效果图[简陋版]

    在这里插入图片描述

    六.小结

    本章使用Django框架实现了对数据库的增加以及查询功能的实现,和html中的少量模板语法,实现方法不只这一种,各位感兴趣的小伙伴,可以去试一试.
    有哪里不足或者有更好的建议,欢迎留言吐槽,有哪里不懂的小伙伴可以私信我,我会一一答复,感谢认可,感谢支持!

  • 相关阅读:
    01,完全,多重,混合,分组背包相关题目
    Stream filter()过滤有效数据
    ocr、人工智能、文字识别接口
    LibOpenCM3(二) 项目模板 Makefile分析
    第二十二天-Pandas
    字符串的常用方法
    redhat8下载配置jdk1.8和jdk11
    【SmartApi】v1.1.0版本发布
    css写出来显示不出来,而且背景直接没有显示出来
    Codeforces暑期训练周报(8.15~8.21)
  • 原文地址:https://blog.csdn.net/weixin_45539338/article/details/125627570