Django常見錯誤總結

ImportError: No module named 'MySQLdb'


解決方法:

1. 安裝pymysql模塊

2. 在app的__init__.py文件中寫入以下內容


    import pymysql

    

    pymysql.install_as_MySQLdb()


----------------------------------------------------------------------------------------------------------------


ImportError: cannot import name 'Thing2Literal'

AttributeError: module 'pymysql' has no attribute 'install_as_MySQLdb'


解決方法:

1. pip3 uninstall PyMySQL3

2. pip3 install -U --force-reinstall pymysql


----------------------------------------------------------------------------------------------------------------


You are trying to add a non-nullable field 'publication_date' to book 

without a default; we can't do that (the database needs something to populate existing rows).

Please select a fix:

 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)

 2) Quit, and let me add a default in models.py


解決方法:

這個錯誤常見於後期修改了model.py文件,在做數據庫同步時報錯,只要把這個新增字段允許爲空即可!

因爲默認字段是非空,所以設置字段允許爲空(曾嘗試設置default="",migrate同步失敗)

示例:publication_date = models.DateField(null=True)


----------------------------------------------------------------------------------------------------------------


pymysql.err.InternalError: (1050, "Table 'app01_authordetail' already exists")


解決方法:

因爲錯誤同步,導致正確的表結構無法同步過去,只能刪除舊錶再同步,適用於測試數據庫。如果數據庫中有重要的數據庫千萬別這麼幹!

1. 刪除app/migrations/下除__init__.py外所有的py文件;

2. 登錄數據庫刪除所有的表;

3. 將數據庫中django_migrations表中相關的同步記錄刪除;

4. 再次同步 python3 manage.py makemigrations; python3 manage.py migrate


----------------------------------------------------------------------------------------------------------------


'QuerySet' object has no attribute 'book_set'


解決方法:

QuerySet沒有_set方法,必須是Object纔可以,所以使用[0]將對象從列表中取出

示例:

obj = Publisher.objects.filter(name="機械出版社")[0]

print(obj.book_set.all().values("title"))


----------------------------------------------------------------------------------------------------------------

django.db.utils.OperationalError: no such table: django_session


解決方法:

這是因爲還沒有進行數據庫同步,數據庫中還沒有創建相關聯的表

python3 manage.py makemigrations

python3 manage.py migrate


----------------------------------------------------------------------------------------------------------------

RuntimeWarning: DateTimeField received a naive datetime


報錯原因:

from django.utils import timezone

In[3]: timezone.now()

Out[3]: 

datetime.datetime(2017, 10, 22, 11, 33, 22, 688117, tzinfo=<UTC>)

In[4]: from datetime import datetime

In[5]: datetime.now()

Out[5]: 

datetime.datetime(2017, 10, 22, 19, 33, 38, 60812)


這是由於Django默認使用的時間都是帶時區的,而我們在插入數據時使用的datetime是不帶時區的。

解決方法:

方案一:

把setting.py文件中USE_TZ改爲false,默認不使用時區

方案二:

        pip3 install pytz

import pytz

datetime.now(tz=pytz.UTC)

導入pytz模塊,datetime生成時間時帶上時區


----------------------------------------------------------------------------------------------------------------

Got an error creating the test database: (1007, "Can't create database 'test_django_db'; database exists")

Type 'yes' if you would like to try deleting the test database 'test_django_db', or 'no' to cancel: 


原因:

Django test數據庫自動生成的數據庫字符集是latin1,不是utf8,所以當表中有中文會報錯


解決方法:

https://docs.djangoproject.com/en/1.11/ref/settings/#charset

設置test數據庫字符集爲“utf8”

DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.mysql',

        'NAME': 'django_db',

        'USER': 'root',

        'PASSWORD': 'mysql',

        'HOST': '',

        'PORT': '',

        'TEST': {'CHARSET': 'utf8', },

    }

}


----------------------------------------------------------------------------------------------------------------

UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list:\


原因:

因爲obj.objects.all()的結果是無序的,Paginator分頁會出錯


解決方法:

在查詢結果上加上order_by排序, obj.objects.all().order_by("id")


-----------------------------------------------------------------------------------------------------------------

setting.py文件中設置的時區是"Asia/Shanghai",數據庫中存儲的時間是UTC時間,模板中按照資料說應該自動渲染成東八區,

但是沒有,要麼手動給他增加8個小時,要麼通過astimezone方法更改它的時區


解決方法(column_data是帶時區的時間):

import pytz

from django.utils.timezone import datetime, timedelta


tz = pytz.timezone("Asia/Shanghai")


# 笨方法:

column_data = (column_data + timedelta(hours=8)).replace(tzinfo=tz).strftime("%Y-%m-%d %H:%M:%S %Z")

# 聰明方法:

column_data = column_data.astimezone(tz=tz).strftime("%Y-%m-%d %H:%M:%S %Z")


-----------------------------------------------------------------------------------------------------------------


# 如果手動修改了數據庫中的記錄,再migration同步時會出錯


解決方法:

1. python3 manage.py makemigrations

2. python3 manage.py migrate --fake












發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章