mysql> create database HelloDjango charset=utf8;
Query OK, 1 row affected (0.01 sec)
安装pymysql
pip install pymysql -i https://pypi.douban.com/simple
(venv) MacBookPro:HelloDjango zhangxm$ pip install pymysql
Collecting pymysql
Downloading https://files.pythonhosted.org/packages/ed/39/15045ae46f2a123019aa968dfcba0396c161c20f855f11dea6796bcaae95/PyMySQL-0.9.3-py2.py3-none-any.whl (47kB)
|████████████████████████████████| 51kB 196kB/s
Installing collected packages: pymysql
Successfully installed pymysql-0.9.3
WARNING: You are using pip version 19.3.1; however, version 20.0.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
安装上以后系统仍然是不认这个库的,pymysql伪装成mysqlclient
比较常用的伪装写在程序的__init__.py中
import pymysql
pymysql.install_as_MySQLdb()
##解决方法 仍然使用pymysql
1 )配置文件的目录中_init_.py中有如下代码
import pymysql
pymysql.install_as_MySQLdb() # 这是一个hack,为了在Djano中替代默认的mysqlclient。mysqlclient官方描述:This is a fork of MySQLdb1
2) 点进去install_as_MySQLdb
找到version_info变量,改成
version_info = (1, 3, 13, "final", 0)
3) 改变django.db.backends.mysql.operations.py的一行代码
query = query.decode(errors='replace') -> query = query.encode(errors='replace')
原因:mysqlclient returns bytes object, PyMySQL returns str object
参考:https://github.com/PyMySQL/PyMySQL/issues/790#issuecomment-484201388
想要承认项目的存在,更改project settings文件:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'App',
'Two',
'Three'
# 'Three.apps.ThreeConfig' #1.9之后可以这样写
]
然后写Three里的路由规则
from django.conf.urls import url
from Three import views
urlpatterns = [
url('^index/', views.index),
]
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
from django.template import loader
def index(request):
three_index = loader.get_template("three_index.html")
context ={"student_name": '张三'
}
#有渲染,解析渲染引擎表达式的作用,如果不需要这些,直接open也可以
result = three_index.render(context=context)
print(result)
return HttpResponse(result)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Three_Index</title>
</head>
<body>
<h2>Three Index</h2>
{{ student_name }}
</body>
</html>
python shell
原文:https://www.cnblogs.com/xidianzxm/p/12257952.html