django2.2简单配置-mysql

一. 主要演示django2.2如何配置mysql数据库

1.安装pymysql模块
pip isntall pymysql
2.在setting中注释掉默认的数据库.添加mysql配置
import pymysql
pymysql.install_as_MySQLdb()
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mysite',
        'HOST': '47.104.124.214',
        'USER': 'root',
        'PASSWORD': 'django',
        'PORT': '3306',
    }
}
3.setting文件添加app应用
INSTALLED_APPS = [
    'xxxxxx',
]
4.修改字体时区
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'

5.建立模板目录及静态资源存放目录并添加配置
在app同级目录下建立目录
mkdir templates
mkdir static
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
    },
]
在setting中最后添加
STATIC_PATH = os.path.join(BASE_DIR,'static')
STATICFILES_DIRS = (STATIC_PATH,)

6.配置mysql建立数据库-----重点
cat models.py
from django.db import models
#建立一个User表
class User(models.Model):
    user = models.CharField(max_length=30)
    passwd = models.CharField(max_length=30)
 def __str__(self): return self.user class Meta: db_table = 'User' verbose_name = '用户表[User]' verbose_name_plural = '用户表[User]'
   #__str__是python的一个魔幻方法。做用于django管理界面用于将数据库中的记录展现为易读的字符串。 #Meta类用于定义表名称。默认表名称为'app名称_表名称',db_table用于指定表名 #verbose_name用于在admin界面单数显示,verbose_name_plural复数形式显示。中文单数复数通常不作区别。 #verbose相似于User表在admin界面的显示形式。相似于别名 
7.生产数据库: 切记手动建立数据库且设置数据编码为utf8
python manage.py makemigrations #生产差别数据文件
python manage.py migrate #生产数据表
python manage.py createsuperuser #建立管理员root

8.注册数据库:
vi admin.py
from django.contrib import admin
from . import models
admin.site.register(models.User)

9.python manage.py runserver 0.0.0.0:80 开启服务

查看admin界面User表显示的为‘用户表[User]’。此属性与咱们verbose_name设置有关



查看数据,数据显示的为咱们的定义名称。此属性与咱们__str__函数返回的return self.user字段有关。



表名称默认为'app名称_表名'因为咱们经过db_table = 'User'指定了表名因此建立为User表。

二. 简单演示路由配置和views.py视图文件编写

简单编写views.pyhtml

from django.shortcuts import render from django.http import HttpResponse

def index(request): return HttpResponse('Hello, world. You\'re at the polls index.')

在app下建立路由文件urls.pypython

from django.urls import path
from . import views
urlpatterns = [
    path('', views.index,name='index'),
]

在最外层项目路由文件中配置:mysql

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

urlpatterns = [
    path('',include('Registration.urls')),
    path('admin/', admin.site.urls),
    path('Registration/',include('Registration.urls'))
]

三问题汇总:

报错1:
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is requ
ired; you have 0.9.3.
解决:
vi Python36-32\Lib\site-packages\django\db\backends\mysql\base.py
注释一下内容:
#if version < (1, 3, 3):
#    raise ImproperlyConfigured("mysqlclient 1.3.3 or newer is required; you have %s" % Database.__version__)
vi Python36-32\Lib\site-packages\django\db\backends\mysql\__init_.py
插入一下内容
import pymysql
pymysql.install_as_MySQLdb()

报错2
File “/home/wuchunhui/.virtualenvs/sss/lib/python3.5/site-packages/django/db/backends/mysql/operations.py”, line 146, in last_executed_query
query = query.decode(errors=‘replace’)
AttributeError: ‘str’ object has no attribute ‘decode’

解决:
vi /home/wuchunhui/.virtualenvs/sss/lib/python3.5/site-packages/django/db/backends/mysql/operations.py
将一下内容注释
#if query is not None:
#    query = query.decode(errors=‘replace’)
#    return query

报错3:
File "D:\Python\Python37-32\lib\site-packages\django\views\debug.py", line 332, in get_traceback_html
t = DEBUG_ENGINE.from_string(fh.read())  
UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6 in position 9737: illegal multibyte sequence
解决:
打开django/views下的debug.py文件,转到line331行:
with Path(CURRENT_DIR, 'templates', 'technical_500.html').open() as fh
将其改为:
with Path(CURRENT_DIR, 'templates', 'technical_500.html').open(encoding="utf-8") as fh
就成功了。
报错4:
Please enter the default value now, as valid Python
You can accept the default 'timezone.now' by pressing 'Enter' or you can provide another value.
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
解决: 选择1执行: timezone.now()

报错:5 删除数据库后没法重建
0.删除数据库
1.删除app下migrations除了:_init_.py和_pycache_以外的其余全部内容
3.python manage.py makemigrations #生产差别数据文件
 python manage.py migrate #生产数据表
 python manage.py createsuperuser #建立管理员root
相关文章
相关标签/搜索