Django视图之ORM更改数据库连接——配置MySQL库

Django中创建app01应用

python manage.py startapp app01

1. 首先安装pymsql模块

# Python3中
pip3 install pymysql

在 python2 中,使用 pip install mysql-python 进行安装连接MySQL的库,使用时 import MySQLdb 进行使用

在 python3 中,改变了连接库,改为了 pymysql 库,使用pip install pymysql 进行安装,直接导入即可使用

但是在 Django 中, 连接数据库时使用的是 MySQLdb 库,这在与 python3 的合作中就会报以下错误了

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'

解决方法:在 settins.py配置文件相同目录下__init__.py 文件中添加以下代码即可

import pymysql
pymysql.install_as_MySQLdb()

2 启动Django项目

python manage.py runserver 8000

默认不写IP地址为127.0.0.1  

3 配置setting连接MySQL

a.      INSTALLED_APPS中添加app01应用

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

b. 注销掉DATABASES中sqlit3数据库的配置

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'blog',
        'USER': 'root',
        'PASSWORD': '123.com',
        'HOST': '10.0.0.10',
        'PORT': '3306',
    }
}

c.   在MySQL数据库中创建blog库

MariaDB [(none)]> create database blog;

4 初始化数据库

python manage.py makemigrations app01
python manage.py migrate

5 在models中创建Book类

from django.db import models
class UserType(models.Model):
    '''
    用户类型
    '''
    title = models.CharField(max_length=12)


class UserInfo(models.Model):
    '''
    用户表
    '''
    name = models.CharField(max_length=16)
    age = models.IntegerField()
    ut = models.ForeignKey('UserType')


class Book(models.Model):
    nid = models.AutoField(primary_key=True)
    title = models.CharField(max_length=32)
    author = models.CharField(max_length=32)
    publishDate = models.DateField()    #日期类型
price = models.DecimalField( max_digits=5,decimal_places=2)

说明:
max_digits:最大多少个数字
decimal_places:小数点保留几位

6 urls配置地址映射

urlpatterns = [
    url(r'^index/', views.index),
    url(r'^del/', views.delBook),
    url(r'^edit/', views.editBook),
    url(r'^add/', views.addBook),
]

7 需求功能实现

要求:
1.	当用户访问index的数据,展示所有书籍信息(书名,作者,发布日期,价格);
2.	主页index有添加,编辑及删除的功能,当点击相应的图标要实现相应的功能;
扩展:
在主页index页面中添加一个模态对话框添加书籍信息

8 主页index展示

 

模态框

 

9 views删除函数

def delBook(request):
    nid=request.GET.get('nid')
    models.Book.objects.filter(nid=nid).delete()

    return redirect('/index/')

10 views编辑函数

a views文件编写

def editBook(request):
    if request.method=="GET":
        id=request.GET.get('nid')
        bookInfo=models.Book.objects.filter(nid=id).first()
        print(bookInfo.nid)
        return render(request,'edit.html',{'bookInfo':bookInfo})
    else:
        nid=request.POST.get('nid')
        title=request.POST.get('title')
        author=request.POST.get('author')
        publishDate=request.POST.get('publishDate')
        price=request.POST.get('price')
        #更新数据库
        models.Book.objects.filter(nid=nid).update(title=title,author=author,publishDate=publishDate,price=price)


        return redirect('/index/')

b edit.html静态文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.min.css">
    <style>
        .container {
            margin-top: 100px;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="row col-md-offset-2">
        <form class="form-horizontal " method="POST" action="/edit/">
            <input type="text" style="display: none;" name="nid" value={{ bookInfo.nid }}>
            <div class="form-group">
                <label for="book" class="col-sm-2 control-label">书名</label>
                <div class="col-sm-4">
                    <input type="text" class="form-control" id="book" placeholder="book" name="title" value={{ bookInfo.title }}>
                </div>
            </div>
            <div class="form-group">
                <label for="author" class="col-sm-2 control-label">作者</label>
                <div class="col-sm-4">
                    <input type="text" class="form-control" id="author" placeholder="author" name="author" value={{ bookInfo.author }}>
                </div>
            </div>
            <div class="form-group">
                <label for="date" class="col-sm-2 control-label">出版日期</label>
                <div class="col-sm-4">
                    <input type="text" class="form-control" id="date" placeholder="date" name="publishDate" value={{ bookInfo.publishDate|date:"Y-m-d" }}>
                </div>
            </div>
            <div class="form-group">
                <label for="price" class="col-sm-2 control-label">价格</label>
                <div class="col-sm-4">
                    <input type="text" class="form-control" id="price" placeholder="price" name="price" value={{ bookInfo.price }}>
                </div>
            </div>


            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-4">
                    <button type="submit" class="btn btn-success">添加</button>
                </div>
            </div>

        </form>
    </div>
</div>


</body>
</html>

 

11 views添加函数

a views文件编写

def addBook(request):
    if request.method=='GET':
        return render(request,'add.html')
    else:
        title=request.POST.get('title')
        author=request.POST.get('author')
        publishDate=request.POST.get('publishDate')
        price=request.POST.get('price')
        print(title,author,publishDate,price)
        models.Book.objects.create(title=title,author=author,publishDate=publishDate,price=price)
        return redirect('/index/')

b add.html静态文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.min.css">
    <style>
        .container {
            margin-top: 100px;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="row col-md-offset-2">
        <form class="form-horizontal " method="POST" action="/add/">
            <div class="form-group">
                <label for="book" class="col-sm-2 control-label">书名</label>
                <div class="col-sm-4">
                    <input type="text" class="form-control" id="book" placeholder="book" name="title" >
                </div>
            </div>
            <div class="form-group">
                <label for="author" class="col-sm-2 control-label">作者</label>
                <div class="col-sm-4">
                    <input type="text" class="form-control" id="author" placeholder="author" name="author" >
                </div>
            </div>
            <div class="form-group">
                <label for="date" class="col-sm-2 control-label">出版日期</label>
                <div class="col-sm-4">
                    <input type="text" class="form-control" id="date" placeholder="date" name="publishDate" >
                </div>
            </div>
            <div class="form-group">
                <label for="price" class="col-sm-2 control-label">价格</label>
                <div class="col-sm-4">
                    <input type="text" class="form-control" id="price" placeholder="price" name="price" >
                </div>
            </div>


            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-4">
                    <button type="submit" class="btn btn-success">添加</button>
                </div>
            </div>

        </form>
    </div>
</div>


</body>
</html>

 

12 模态框添加

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.min.css">
    <style>
        .container {
            margin-top: 100px;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-7  col-md-offset-3">
            <div class="">
                <a href="/add/">
                    <button class="pull-right btn btn-primary">添加</button>
                </a>
            </div>
		<!-- Button模态对话框 -->
            <div class="">
                <a>
                    <button type="button" class="btn btn-info " data-toggle="modal" data-target="#myModal">
                        模态框添加
                    </button>
                </a>
            </div>

            <table class="table table-striped table-responsive table-bordered">
                <thead>
                <tr>
                    <th>编号</th>
                    <th>书名</th>
                    <th>作者</th>
                    <th>出版日期</th>
                    <th>价格</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                {% for book_obj in bookList %}
                    <tr>
                        <td>{{ book_obj.nid }}</td>
                        <td>{{ book_obj.title }}</td>
                        <td>{{ book_obj.author }}</td>
                        <td>{{ book_obj.publishDate|date:"Y-m-d" }}</td>
                        <td>{{ book_obj.price }}¥</td>
                        <td>
                            <a href="/edit/?nid={{ book_obj.nid }}">
                                <button class="btn btn-success">编辑</button>
                            </a>
                            <a href="/del/?nid={{ book_obj.nid }}">
                                <button class="btn btn-danger">删除</button>
                            </a>
                        </td>
                    </tr>
                {% endfor %}
                </tbody>

            </table>
        </div>
    </div>
</div>

<!-- Modal模态对话框 -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">添加书籍</h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <form class="form-horizontal" method="POST" action="/add/">
                        <div class="form-group">
                            <label for="book" class="col-sm-3 control-label">书名</label>
                            <div class="col-sm-6">
                                <input type="text" class="form-control" id="book" placeholder="book" name="title">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="author" class="col-sm-3 control-label">作者</label>
                            <div class="col-sm-6">
                                <input type="text" class="form-control" id="author" placeholder="author"
                                       name="author">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="date" class="col-sm-3 control-label">出版日期</label>
                            <div class="col-sm-6">
                                <input type="text" class="form-control" id="date" placeholder="date"
                                       name="publishDate">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="price" class="col-sm-3 control-label">价格</label>
                            <div class="col-sm-6">
                                <input type="text" class="form-control" id="price" placeholder="price" name="price">
                            </div>
                        </div>

                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                            <button type="submit" class="btn btn-success">保存</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>


<script src="/static/bootstrap-3.3.7/js/jquery-3.2.1.js"></script>
<script src="/static/bootstrap-3.3.7/js/bootstrap.min.js"></script>
</body>
</html> 

13 静态文件static目录配置  

STATICFILES_DIRS = (
    # os.path.join(BASE_DIR,'static','css'),  #'static' 实际目录名称'css'  别名
    os.path.join(BASE_DIR,'static'),  #'static' 实际目录名称'css'  别名
)

目录结构:

 

posted @ 2017-10-25 17:17  Pythia丶陌乐  阅读(354)  评论(0编辑  收藏  举报