Django常见错误总结

ImportError: No module named 'MySQLdb'python


解决方法:mysql

1. 安装pymysql模块sql

2. 在app的__init__.py文件中写入如下内容数据库


    import pymysqldjango

    

    pymysql.install_as_MySQLdb()session


----------------------------------------------------------------------------------------------------------------app


ImportError: cannot import name 'Thing2Literal'ide

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


解决方法:ui

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

相关文章
相关标签/搜索