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
相關文章
相關標籤/搜索