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

本文转自戴柏阳的博客博客51CTO博客,原文链接http://blog.51cto.com/daibaiyang119/2066741如需转载请自行联系原作者


daibaiyang119

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值