Python3.6 + Django2 + MySQL 实现数据插入和查询

虾米姐 阅读:681 2021-03-31 18:17:47 评论:0

环境要求:

Windows7、Python3.7、Django2、MySQL8

功能要求实现:

1、实现用户注册

2、展示用户信息

项目搭建步骤:

1、创建项目(sutdentsite)

django-admin startproject sutdentsite

2、创建应用(student)

python manage.py startapp student

项目结构文件说明:

sutdentsite: 项目的容器。
manage.py: 一个实用的命令行工具,可让你以各种方式与该 Django 项目进行交互。
sutdentsite/__init__.py: 一个空文件,告诉 Python 该目录是一个 Python 包。
sutdentsite/settings.py: 该 Django 项目的设置/配置。
sutdentsite/urls.py: 该 Django 项目的 URL 声明; 一份由 Django 驱动的网站"目录"。
sutdentsite/wsgi.py: 一个 WSGI 兼容的 Web 服务器的入口,以便运行你的项目。

应用结构文件说明:

student:应用的容器

student/admin.py:Django自带了一个管理界面,这个文件可以注册model在界面中管理

student/__init__.py:无

student/migrations:用来初始化数据库,在执行python manage.py makemigrations 的时候会自动生成一个文件在这里

student/migrations/__init__.py:表明migrations也是一个包

student/models.py:在这个文件里面定义model类

student/tests.py:写测试代码

student/views.py:视图,Django映射urls.py里面的url的时候,在views.py里面查找对应的处理方法

3、项目(sutdentsite)添加模板文件:template

4、项目(sutdentsite)编辑配置文件setting

4.1 调整时区

LANGUAGE_CODE = 'zh-hans' 
 
TIME_ZONE = 'Asia/Shanghai' 
 
USE_I18N = True 
 
USE_L10N = True 
 
USE_TZ = True

4.2 添加应用(student)

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

4.3 配置MySQL 数据库连接:

DATABASES = { 
    'default': { 
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'student', 
        'USER': 'root', 
        'PASSWORD': '123456', 
        'HOST': '127.0.0.1', 
        'PORT': '3306', 
        'OPTIONS': {'charset': 'utf8mb4'}, 
    } 
}

4.4、移除crsf 中间件

MIDDLEWARE = [ 
    'django.middleware.security.SecurityMiddleware', 
    'django.contrib.sessions.middleware.SessionMiddleware', 
    'django.middleware.common.CommonMiddleware', 
    # 关闭Django的跨站请求保护机制 
    # 'django.middleware.csrf.CsrfViewMiddleware', 
    'django.contrib.auth.middleware.AuthenticationMiddleware', 
    'django.contrib.messages.middleware.MessageMiddleware', 
    'django.middleware.clickjacking.XFrameOptionsMiddleware', 
]

4.5、配置template 文件夹

TEMPLATES = [ 
    { 
        'BACKEND': 'django.template.backends.django.DjangoTemplates', 
        # 模板文件绝对路径写法 
        'DIRS': ['E:/python_workspace/sutdentsite/template'], 
        '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', 
            ], 
        }, 
    }, 
]

5、用户数据库设计

student/model.py创建用户信息表

from django.db import models 
 
# Create your models here. 
 
 
class UserInfo(models.Model): 
    username = models.CharField(max_length=50) 
    password = models.CharField(max_length=50) 
    address = models.CharField(max_length=200) 
    email = models.EmailField() 
    create_date = models.DateField() 
    age = models.CharField(max_length=20) 
    sex = models.CharField(max_length=20) 
 
 
class User(models.Model): 
    user_name = models.CharField(max_length=20) 
    user_password = models.CharField(max_length=20) 
    user_email = models.EmailField() 
    user_address = models.CharField(max_length=500) 
    user_cards = models.CharField(max_length=20) 
    user_numbers = models.CharField(max_length=20) 

在终端Terminal 项目目录下执行数据表更新命令:

python manage.py makemigrations

python manage.py migrate

 

6、在student目录下views.py增加两个函数insert 注册信息 和lists 查询信息

from django.shortcuts import render, redirect 
from . import models 
# 引入模块 
from django.utils.timezone import now 
 
 
# Create your views here. 
 
 
def lists(req): 
    data = {} 
    listdata = models.UserInfo.objects.all() 
    data['list'] = listdata 
    return render(req, 'lists.html', data) 
 
 
# 路由中指定要调用的函数,传入一个用户请求参数 
def index(request): 
    # 返回HTML页面时,使用render来渲染和打包 
    return render(request, 'index.html') 
 
 
def insert(request): 
    if request.method == 'GET': 
        return render(request, 'register.html') 
    elif request.method == "POST": 
        username = request.POST.get("username", None) 
        password = request.POST.get("password", None) 
        mail = request.POST.get("email", None) 
        age = request.POST.get("age", None) 
        address = request.POST.get("address", None) 
        models.UserInfo.objects.create(username=username, password=password, email=mail, age=age, address=address, 
                                       create_date=now()) 
        return redirect('student:lists') 

7、在student下增加一个url.py,并添加student 应用的命名空间

from django.conf.urls import url 
from . import views 
# include()函数允许引用其他的 URLconf。每当 django 遇到 include(),它会截取 URL 
# 中匹配到的前面的部分,并将剩余部分的字符串发送给包含的 URLconf 做进一步处理 
app_name = 'student' 
urlpatterns = [ 
    url('lists/', views.lists, name='lists'), 
    url('register/', views.insert, name='register'), 
    url('index/', views.index), 
] 

然后在sutdentsite目录下的urls.py文件中,添加student应用的url 路径引用

"""sutdentsite URL Configuration 
 
The `urlpatterns` list routes URLs to views. For more information please see: 
    https://docs.djangoproject.com/en/2.1/topics/http/urls/ 
Examples: 
Function views 
    1. Add an import:  from my_app import views 
    2. Add a URL to urlpatterns:  path('', views.home, name='home') 
Class-based views 
    1. Add an import:  from other_app.views import Home 
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home') 
Including another URLconf 
    1. Import the include() function: from django.urls import include, path 
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls')) 
""" 
from django.contrib import admin 
from django.urls import path 
from django.conf.urls import include 
 
urlpatterns = [ 
    path('admin/', admin.site.urls), 
    path('student/', include('student.urls', namespace='student')), 
] 

8、在template模板目录下创建两个html文件,用于用户注册和用户信息展示

register.html

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>用户注册</title> 
<STYLE type="text/css"> 
        #login{ 
            width:400px; 
            height:280px; 
            position:absolute; 
            left: 50%; 
            top: 50%; 
            margin-left:-200px; 
            margin-top:-140px; 
            border:1px; 
            background-color:white; 
            align:center; 
 
} 
        #form{ 
            width:300px; 
            height:160px; 
            position:relative; 
             left:50%; 
              top:50%; 
              margin-left:-150px; 
              margin-top:-80px; 
 
        } 
 
    </STYLE> 
 
  </head> 
 
  <body> 
    <div id="login"> 
        <div id="form"> 
		    <form id='addForm' action="{% url 'student:register' %}" method="post"> 
		     <div class="form-group"> 
		        <label for="name">姓    名:</label> 
		        <input type="text" name="username" placeholder="请输入用户名" required/> 
		     </div> 
		     <div class="form-group"> 
		        <label for="name">密    码:</label> 
		        <input type="password" name="password" placeholder="请输入密码" required/> 
		     </div> 
		     <div class="form-group"> 
		        <label for="name">邮    箱:</label> 
		        <input type="mail" name="email" placeholder="请输入邮箱地址" required/> 
		     </div> 
		     <div class="form-group"> 
		        <label for="name">年纪:</label> 
		        <input type="text" name="age" placeholder="请输入正确的手机号" required/> 
		     </div> 
		     <div class="form-group"> 
		        <label for="name">住    址:</label> 
		        <input type="address" name="address" placeholder="请输入你现在的住址" required/> 
		     </div> 
		        <input type="submit" value="提交"  align="right"> 
		    </form> 
        </div> 
    </div> 
  </body> 
</html>

lists.html

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>用户列表</title> 
    <!-- Bootstrap 相关文件 --> 
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css"> 
	<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script> 
	<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script> 
</head> 
<body> 
    <ul class="breadcrumb"> 
        <li><a href="/">Home</a></li> 
        <li><a href="#">2018</a></li> 
        <li class="active">十一月</li> 
    </ul> 
    <table class="table"> 
	<caption>用户列表</caption> 
   <thead> 
      <tr> 
         <th>ID</th> 
         <th>账户</th> 
         <th>密码</th> 
         <th>地址</th> 
         <th>时间</th> 
      </tr> 
   </thead> 
   <tbody> 
      {% for d in list %} 
      <tr> 
         <td>{
  
   { d.id }}</td> 
         <td>{
  
   { d.username }}</td> 
         <td>{
  
   { d.password }}</td> 
         <td>{
  
   { d.address }}</td> 
         <td>{
  
   { d.create_date }}</td> 
      </tr> 
      {% endfor %} 
   </tbody> 
</table> 
</body> 
</html>

效果展示:

源代码下载地址:

 

标签:Django
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号