Django框架,以MVT(mvc+T)模式高效开发web,超越spring系列的存在
Django 操作Mysql(增加数据)
版本
- Django:2.0.5
- Python:3
- Mysql:5.7.20
- PyMySQL:0.8.0
一、配置数据库(包括model层)
1.配置mysql连接
1 2 3 4 5 6 7 8 9 10 11 12
| DATABASES = { 'default': { #'ENGINE': 'django.db.backends.sqlite3', #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'ENGINE': 'django.db.backends.mysql', 'NAME': 'testdata', 'USER': 'root', 'PASSWORD': 'xxxxx', #数据库密码 'HOST': '127.0.0.1', 'PORT': '3306' } }
|
2.注册app
命令行生成app
需要先在__init__.py文件中导入pymysql,参见后面数据库操作1
1
| >python manage.py startapp appname
|
再在配置文件中配置
1 2 3 4 5 6 7 8 9
| INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'appname' #最后一行加上app名 ]
|
定义models.py中的类
1 2 3 4 5 6 7 8 9 10
| # -*- coding: utf-8 -*- from __future__ import unicode_literals
from django.db import models
# Create your models here.
class message(models.Model): username = models.CharField(max_length=20) password = models.CharField(max_length=15)
|
二、数据库操作(models->mysql)
1.pymysql
区别于python2,python3中没有MysqlDB,所以python3不能连接到数据库,会报错”no modul MysqlDB”,替代包有pyMySQL,Mysqlclient.
在站点文件中的__init__.py中导入
1 2
| import pymysql pymysql.install_as_MySQLdb()
|
2.命令行操作
生成数据库迁移类
1
| python manage.py makemigrations appname
|
把迁移类迁移到数据库
1
| python manage.py migrate
|
- 数据库操作
迁移前
1 2 3
| >mysql -u root -p >password >create database testdata
|
迁移后
1 2 3 4 5
| >show databases; >use testdata; >show tables; >desc appname_message >select * from appname_message
|
三、view层
1 2 3
| from __future__ import unicode_literals from appname import models from django.shortcuts import render_to_response
|
定义insert函数,用于将网页数据插入到数据库
1 2 3 4 5 6
| def insert(request): if request.method == "POST": username = request.POST.get("username", None) password = request.POST.get("password", None) models.message.objects.create(username=username, password=password) return render_to_response('insert.html')
|
定义list函数,用于将数据库数据显示到网页
1 2 3
| def list(request): people_list = models.message.objects.all() return render_to_response("showuser.html",{"people_list":people_list})
|
四、control层(urls.py)
控制访问路径
1 2 3 4 5 6 7 8 9
| from django.conf.urls import url from django.contrib import admin from appname import views
urlpatterns = [ url(r'^insert/',views.insert), url(r'^show/',views.list), url(r'^admin/', admin.site.urls), ]
|
五、网页部分(templates)
在根文件夹下创建templates文件夹,并在setting.py中配置TEMPLATES的’DIRS’
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(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', ], }, }, ]
|
插入数据页面insert.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>用户登录</title> </head> <body> <form action="/insert/" method="post"> <input type="text" name="username"/> <input type="password" name="password"/> <input type="submit" value="提交"> </form> </body> </html>
|
显示数据页面showuser.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>信息展示</h1> <table <tr> <th>用户名</th> <th>密码</th> </tr> {% for line in people_list %} <tr> <td>{{line.username}}</td> <td>{{line.password}}</td> </tr> {% endfor %} </table> </body> </html>
|
六、csrf报错
页面提交数据报错(403),在setting.py中关闭CSRF
1 2 3 4 5 6 7 8 9
| MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
|
-参考:
https://blog.csdn.net/yf999573/article/details/53081196
https://blog.csdn.net/it_dream_er/article/details/52093362