Python Django学习之数据库

接https://www.cnblogs.com/rainbow-tan/p/13385754.html

1、创建数据库

create database DjangoDB default charset=utf8;

2、配置数据库信息

在settings.py中添加代码

3、创建数据库模型

python D:\Python37\Scripts\django-admin.py startapp Model

创建后项目目录

4、settings.py配置模型

5、下载并配置mysql包

去https://www.lfd.uci.edu/~gohlke/pythonlibs/下载对应MySQLclient

安装命令

pip install mysqlclient-1.2.10-cp27-cp27m-win32.whl

settings.py同级目录中的__init__.py添加代码

import pymysql

pymysql.install_as_MySQLdb()

6、定义表结构

在models.py中添加代码

from django.db import models

# Create your models here.
class user_info(models.Model):
    account = models.CharField(max_length=20,primary_key=True,null=False)
    password=models.CharField(max_length=20,null=False)
    username=models.CharField(max_length=20,null=True)
    birthday=models.DateTimeField(null=True)
    sex=models.CharField(max_length=8,null=True)

7、与数据库交互

python manage.py migrate
python manage.py makemigrations Model
python manage.py migrate Model

运行后数据库如下

 如果出现错误提示raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)

则注释D:\Python37\Lib\site-packages\django\db\backends\mysql\base.py中错误提示代码(原因是 MySQLclient不支持python3.4以上)

 8、增删改查

在settings.py同级添加dbmode.py

from django.db import models

# Create your models here.
class user_info(models.Model):
    account = models.CharField(max_length=20,primary_key=True,null=False)
    password=models.CharField(max_length=20,null=False)
    username=models.CharField(max_length=20,null=True)
    birthday=models.DateTimeField(null=True)
    sex=models.CharField(max_length=8,null=True)

(1)增加

在login.html同级添加database.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>数据库测试</title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/bootstrap-datetimepicker-master/css/bootstrap-datetimepicker.min.css">

    <script src="/static/js/jquery-1.11.3.min.js"></script>
    <script src="/static/js/bootstrap.min.js"></script>
    <script src="/static/bootstrap-datetimepicker-master/js/bootstrap-datetimepicker.min.js"></script>

    
</head>
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#addModal">
    增加
</button>
<!-- 模态框(Modal) -->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                    &times;
                </button>
                <h4 class="modal-title" id="myModalLabel">
                    增加用戶信息
                </h4>
            </div>
            <div class="modal-body">
                
                <div>
                    <form class="form-horizontal" role="form" action="/add_user/" method="POST">
                        {% csrf_token %}
                        <div class="form-group">
                          <label for="firstname" class="col-sm-2 control-label">用户名</label>
                          <div class="col-sm-10">
                            <input type="text" class="form-control" name='account' id="firstname" placeholder="">
                          </div>
                        </div>
                        <div class="form-group">
                          <label for="lastname" class="col-sm-2 control-label">密码</label>
                          <div class="col-sm-10">
                            <input type="text" class="form-control" name='password' id="lastname" placeholder="">
                          </div>
                        </div>
                        <div class="form-group">
                            <label for="lastname" class="col-sm-2 control-label">姓名</label>
                            <div class="col-sm-10">
                              <input type="text" class="form-control" name="username" id="lastname" placeholder="">
                            </div>
                          </div>
                          <div class="form-group">
                            <label for="lastname"  class="col-sm-2 control-label">生日</label>
                            <div class="col-sm-10">
                              <input type="text" name='birthday' class="form-control" id="birthday" placeholder="2020-06-02">
                            </div>
                          </div>
                          <div class="form-group">
                            <label for="lastname" class="col-sm-2 control-label">性別</label>
                            <div class="col-sm-10" >
                            <select class="form-control" name="sex"> 
                              <option>男</option>
                              <option>女</option>
                            </select></div>
                           
                          </div>
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <button type="submit" class="btn btn-default">添加</button>
                                <button type="button" class="btn btn-default"  data-dismiss="modal">关闭</button>
                              </div>
                        </div>
                      </form>
                </div>
            </div>
        </div>
    </div>
</div>
<body >
   
</body>
<script>
   $(function(){
   

   })
</script>

</html>

urls.py添加

 运行

 数据库数据

 (2)查询

database.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>数据库测试</title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    

    <script src="/static/js/jquery-1.11.3.min.js"></script>
    <script src="/static/js/bootstrap.min.js"></script>
    

    
</head>
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#addModal">
    增加
</button>
<a href="/select_user">
    查询
</a>
<!-- 模态框(Modal) -->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                    &times;
                </button>
                <h4 class="modal-title" id="myModalLabel">
                    增加用戶信息
                </h4>
            </div>
            <div class="modal-body">
                
                <div>
                    <form class="form-horizontal" role="form" action="/add_user/" method="POST">
                        {% csrf_token %}
                        <div class="form-group">
                          <label for="firstname" class="col-sm-2 control-label">用户名</label>
                          <div class="col-sm-10">
                            <input type="text" class="form-control" name='account' id="firstname" placeholder="">
                          </div>
                        </div>
                        <div class="form-group">
                          <label for="lastname" class="col-sm-2 control-label">密码</label>
                          <div class="col-sm-10">
                            <input type="text" class="form-control" name='password' id="lastname" placeholder="">
                          </div>
                        </div>
                        <div class="form-group">
                            <label for="lastname" class="col-sm-2 control-label">姓名</label>
                            <div class="col-sm-10">
                              <input type="text" class="form-control" name="username" id="lastname" placeholder="">
                            </div>
                          </div>
                          <div class="form-group">
                            <label for="lastname"  class="col-sm-2 control-label">生日</label>
                            <div class="col-sm-10">
                              <input type="text" name='birthday' class="form-control" id="birthday" placeholder="2020-06-02">
                            </div>
                          </div>
                          <div class="form-group">
                            <label for="lastname" class="col-sm-2 control-label">性別</label>
                            <div class="col-sm-10" >
                            <select class="form-control" name="sex"> 
                              <option>男</option>
                              <option>女</option>
                            </select></div>
                           
                          </div>
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <button type="submit" class="btn btn-default">添加</button>
                                <button type="button" class="btn btn-default"  data-dismiss="modal">关闭</button>
                              </div>
                        </div>
                      </form>
                </div>
            </div>
        </div>
    </div>
</div>
<div style="width: 500px;">
  <table class="table table-bordered">
      <caption>用户信息</caption>
      <thead>
        <tr><td>账号</td><td>密码</td><td>用户名</td><td>生日</td><td>性别</td></tr>
      </thead>
      <tbody>
              {% for i in all_user %}
              <tr>

              {% for j in i.values %}
              <td>{{j}}</td>
              {% endfor %}

          </tr>
              
              {% endfor %}
      </tbody>
  </table>
</div>
<body >
   
</body>
<script>
   $(function(){
   

   })
</script>

</html>
View Code

urls.py

"""FirstDjango URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/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 . import views,dbmode

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.login),
    path('back_data/', views.get_data),
    path('form_commit.html/', views.form_commit_html),
    path('form_commit/', views.form_commit),
    path('form_commit_post/', views.form_commit_post),
    path('database.html/', dbmode.show_database_html),
    path('add_user/', dbmode.add_user),
    path('select_user/', dbmode.select_user),
]

dbmode.py

# -*- coding: utf-8 -*-
from django.shortcuts import render
from datetime import datetime

from Model.models import user_info


def show_database_html(request):
    return render(request, 'database.html')

def add_user(request):
    data=dict()
    account = request.POST['account']
    password = request.POST['password']
    username = request.POST['username']
    birthday = request.POST['birthday']
    birthday=datetime.strptime(birthday,'%Y-%m-%d')
    sex = request.POST['sex']
    user=user_info(account=account,password=password,username=username,birthday=birthday,sex=sex)
    ret=user.save()
    print('ret:{}'.format(ret))
    data['ret']=ret
    return render(request, 'database.html',data)

def select_user(request):
    all_user = user_info.objects.all()
    users=[]
    for user in all_user:
        one_user={}
        one_user['account']=user.account
        one_user['password']=user.password
        one_user['username']=user.username
        one_user['birthday']=str(user.birthday)[:11]
        one_user['sex']=user.sex
        users.append(one_user)
    data=dict()
    data['all_user']=users
    return render(request, 'database.html',data)

运行

(3) 修改,假设修改root的username

database.html

<a href="/update_user">
    修改
</a>

urls.py

path('update_user/', dbmode.update_user),

dbmode.py

def update_user(request):
    user = user_info.objects.get(account='root')
    user.username='root{}'.format(random.randint(1,10))
    user.save()
    return render(request, 'database.html')

运行

 数据库数据

(4)删除,假设删除admin1

database.html

<a href="/delete_user">
    删除
</a>

urls.py

path('delete_user/', dbmode.delete_user),

dbmode.py

def delete_user(request):
    user = user_info.objects.get(account='admin1')
    user.delete()
    return render(request, 'database.html')

运行

 数据库

追加:

9、Q对象查询

q1 = Q()
q1.connector = 'AND'
q1.children.append(('age', 20))
q1.children.append(('sex', '')) 
models.Table1.objects.filter(q1)
q1 = Q()
q1.connector = 'OR'
q1.children.append(('age', 18))
q1.children.append(('age', 20))
models.Table1.objects.filter(q1)
q = Q()

q1 = Q()
q1.connector = 'AND'
q1.children.append(('age', 20))
q1.children.append(('sex', ''))

q2 = Q()
q2.connector = 'OR'
q2.children.append(('age', '18'))
q2.children.append(('sex', ''))

q.add(q1, 'AND')
q.add(q2, 'AND')

models.Table1.objects.filter(q)

10、重定向

 username = request.POST.get("username")
    password = request.POST.get("password")

    if username == 'admin' and password == 'admin':
        response = redirect("/index.html/")
        response.set_cookie("is_admin", True)
    elif username == 'root' and password == 'root':
        response = redirect("/index.html/")
        response.set_cookie("is_admin", False)
    else:
        response = redirect("/login.html/")
    # debug
    # response = redirect("/index.html/")
    return response

 11、多个Model配置url

from django.contrib import admin
from django.urls import path, include

from CRUD import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.login_html),
    path('login.html/', views.login_html),
    path('index.html/', views.index_html),
    path('debug/', views.debug),
    path('login/', views.login),

    path('one/', include('Model.urls')),
    path('two/', include('Model2.urls'))
]

 

posted @ 2020-08-01 20:51  南风丶轻语  阅读(273)  评论(0编辑  收藏  举报