1-Django - 报错集
- centos7 pip安装uwsgi报错
- NameError: name 'Database' is not defined
- ImportError: urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'OpenSSL 1.0.2k-fips 26 Jan 2017'. See: https://github.com/urllib3/urllib3/issues/2168
- UnicodeEncodeError: 'gbk' codec can't encode character '\ufffd' in position 1669: illegal multibyte sequence
- django.template.exceptions.TemplateSyntaxError: 'staticfiles' is not a registered tag library. Must
- django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
- django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.
- NameError: name '_mysql' is not defined
- SyntaxError: Generator expression must be parenthesized
- SyntaxError: Generator expression must be parenthesized (widgets.py, line 151)
- ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'fault_reporting.userinfo', but app 'fault_reporting' isn't installed.
- RuntimeWarning: DateTimeField Message.date received a naive datetime .....
- TypeError: Object of type 'QuerySet' is not JSON serializable
- TypeError: Object of type Decimal is not JSON serializable
- AttributeError: Manager isn't available; 'auth.User' has been swapped for 'app01.UserInfo'
- Database returned an invalid datetime value. Are time zone definitions for your database installed?
- AttributeError: 'str' object has no attribute 'decode'
- UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6 in position 9737: illegal multibyte sequence
- ValueError: source code string cannot contain null bytes
- "block" tag with name "device_list_class" appears more than once
- TypeError: isinstance() arg 2 must be a type or tuple of types
- app02.UserInfo.stu: (fields.E300) Field defines a relation with model 'Student', which is either not installed, or is abstract.
- binascii.Error: Invalid base64-encoded string: number of data characters (221) cannot be 1 more than a multiple of 4
- 'staticfiles' is not a registered tag library.Must be one of:
- django.db.utils.IntegrityError: NOT NULL constraint failed: django_admin_log.user_id
- AttributeError: 'AdminSite' object has no attribute '_registry'
- UnboundLocalError: local variable 'before_import_registry' referenced before assignment
- RuntimeError: 'cryptography' package is required for sha256_password or caching_sha2_password auth methods
- ModuleNotFoundError: No module named 'tencentcloud'
centos7 pip安装uwsgi报错
原因之一就是缺少依赖:
yum install openssl-devel bzip2-devel expat-devel gdbm-devel readline-devel sqlite-devel psmisc libffi-devel tk-devel pcre-devel
完事重新执行安装,如果再报错,就执行:
yum remve openssl-devel
反正就是各种尝试。
NameError: name 'Database' is not defined
centos7 + django3.2 + pymysql + mariadb
在服务器上执行python manage.py runserver
时,发现报错:
(nb) [root@VM-0-12-centos day03]# python manage.py runserver 0.0.0.0:8002
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/threading.py", line 1016, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.10/threading.py", line 953, in run
self._target(*self._args, **self._kwargs)
File "/envs/nb/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "/envs/nb/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 110, i
autoreload.raise_last_exception()
File "/envs/nb/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_except
raise _exception[1]
File "/envs/nb/lib/python3.10/site-packages/django/core/management/__init__.py", line 375, in execute
autoreload.check_errors(django.setup)()
File "/envs/nb/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "/envs/nb/lib/python3.10/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/envs/nb/lib/python3.10/site-packages/django/apps/registry.py", line 114, in populate
app_config.import_models()
File "/envs/nb/lib/python3.10/site-packages/django/apps/config.py", line 301, in import_models
self.models_module = import_module(models_module_name)
File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/envs/nb/lib/python3.10/site-packages/django/contrib/auth/models.py", line 3, in <module>
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "/envs/nb/lib/python3.10/site-packages/django/contrib/auth/base_user.py", line 48, in <module>
class AbstractBaseUser(models.Model):
File "/envs/nb/lib/python3.10/site-packages/django/db/models/base.py", line 122, in __new__
new_class.add_to_class('_meta', Options(meta, app_label))
File "/envs/nb/lib/python3.10/site-packages/django/db/models/base.py", line 326, in add_to_class
value.contribute_to_class(cls, name)
File "/envs/nb/lib/python3.10/site-packages/django/db/models/options.py", line 207, in contribute_to_c
self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
File "/envs/nb/lib/python3.10/site-packages/django/utils/connection.py", line 15, in __getattr__
return getattr(self._connections[self._alias], item)
File "/envs/nb/lib/python3.10/site-packages/django/utils/connection.py", line 62, in __getitem__
conn = self.create_connection(alias)
File "/envs/nb/lib/python3.10/site-packages/django/db/utils.py", line 204, in create_connection
backend = load_backend(db['ENGINE'])
File "/envs/nb/lib/python3.10/site-packages/django/db/utils.py", line 111, in load_backend
return import_module('%s.base' % backend_name)
File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "/envs/nb/lib/python3.10/site-packages/django/db/backends/mysql/base.py", line 35, in <module>
version = Database.version_info
NameError: name 'Database' is not defined
最终的解决办法,就是修改其对应的源码,从报错中找到这个源码文件的位置:
File "/envs/nb/lib/python3.10/site-packages/django/db/backends/mysql/base.py", line 35, in <module>
version = Database.version_info
NameError: name 'Database' is not defined
然后vim /envs/nb/lib/python3.10/site-packages/django/db/backends/mysql/base.py
编辑这个文件,进行修改:
ImportError: urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'OpenSSL 1.0.2k-fips 26 Jan 2017'. See: https://github.com/urllib3/urllib3/issues/2168
centos7 + django3.2 + uWSGI2.0.22 + urllib32.0
在项目部署时,执行uwsgi --ini uwsgi.ini
命令之后,启动没问题,nginx也配上了,前端访问之后,uwsgi报错:
Traceback (most recent call last):
File "/envs/book/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 133, in __call__
response = self.get_response(request)
File "/envs/book/lib/python3.9/site-packages/django/core/handlers/base.py", line 130, in get_response
response = self._middleware_chain(request)
File "/envs/book/lib/python3.9/site-packages/django/core/handlers/exception.py", line 49, in inner
response = response_for_exception(request, exc)
File "/envs/book/lib/python3.9/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception
response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
File "/envs/book/lib/python3.9/site-packages/django/core/handlers/exception.py", line 152, in handle_uncaught_exception
callback = resolver.resolve_error_handler(500)
File "/envs/book/lib/python3.9/site-packages/django/urls/resolvers.py", line 611, in resolve_error_handler
callback = getattr(self.urlconf_module, 'handler%s' % view_type, None)
File "/envs/book/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/envs/book/lib/python3.9/site-packages/django/urls/resolvers.py", line 591, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 855, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "/data/www/book/./book/urls.py", line 20, in <module>
path('api/reader/', include('apps.reader.urls')),
File "/envs/book/lib/python3.9/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 855, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "/data/www/book/./apps/reader/urls.py", line 2, in <module>
from apps.reader.views import account, basic, home, catalog, chapter, add_to_favorites
File "/data/www/book/./apps/reader/views/home.py", line 1, in <module>
import requests
File "/envs/book/lib/python3.9/site-packages/requests/__init__.py", line 43, in <module>
import urllib3
File "/envs/book/lib/python3.9/site-packages/urllib3/__init__.py", line 41, in <module>
raise ImportError(
ImportError: urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'OpenSSL 1.0.2k-fips 26 Jan 2017'. See: https://github.com/urllib3/urllib3/issues/2168
[pid: 2154|app: 0|req: 2/2] 61.48.31.123 () {40 vars in 670 bytes} [Tue Aug 29 10:31:55 2023] GET /favicon.ico => generated 0 bytes in 11 msecs (HTTP/1.1 500) 0 headers in 0 bytes (0 switches on core 0)
参考stackoverflow上面的解决方案,一是升级openssl,二是降级urllib3的版本,我这里选择降级:
# 1. 先卸载urllib3
pip uninstall urllib3 -y
# 2. 再安装低版本的
pip install urllib3==1.26.6
完事之后,重新尝试就好了。
参考:https://stackoverflow.com/questions/76187256/importerror-urllib3-v2-0-only-supports-openssl-1-1-1-currently-the-ssl-modu
UnicodeEncodeError: 'gbk' codec can't encode character '\ufffd' in position 1669: illegal multibyte sequence
python3.10 + win10 + django4.2.3
在实现信号时,我打印了其中的kwargs形参,结果报错了:
截图中显示,第8行的print正常打印了,但到了第9行的打印就报错了,怀疑是print内部调用sys.stdout输出时,编码出了问题。
解决办法就是,在settings.py中,按照如下调整下sys.stdout输出时的编码。
# 解决方式1
# import sys
# sys.stdout.reconfigure(encoding='utf-8')
# 解决方式2,在项目运行时,添加下面的参数到环境变量
import os
os.environ['PYTHONIOENCODING'] = "utf-8"
django.template.exceptions.TemplateSyntaxError: 'staticfiles' is not a registered tag library. Must
django3.2/django4
这个问题有点玄乎,这是在自定义inclusion_tag时,报的错,开始我用的是django4,百度搜索的结果是在配置文件中添加如下一行:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': []
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
# 'django.contrib.auth.context_processors.auth',
# 'django.contrib.messages.context_processors.messages',
],
# 就是下面这一行
"libraries": {"staticfiles": "django.templatetags.static"},
},
},
]
后来我把django版本降到了django3.2,发现不用添加上面一行也行,所以怀疑是django版本的问题,但是换了台电脑,先用的django4,发现也不报错了....
所以,目前的解决办法是,只要你inclusion_tag各个步骤的配置没有问题,那么报这个错,就添加上这一行就行了。
参考:
- https://www.cnblogs.com/yizhipanghu/p/15346297.html
- https://www.oschina.net/question/3917555_2287629
django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
win10 + django3.2
使用pycharm启动django项目,发现报错。注意下图中我的django服务配置,有问题。
解决办法,把settings相关的配置添加上就行了:
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.
执行数据迁移 python manage.py makemigrations 报错如下:
解决方案,注释掉 你的python解释器的Lib/site-packages/django/db/backends/mysql/base.py
中的35和36行代码:
NameError: name '_mysql' is not defined
这个报错我遇到过两次,两次解决方案不同,所以先看解决方式1
解决方案1
centos7.5 + mysql5.7 + django3.2 + mysqlclient2.1.0 + python3.9.9
这是在Linux上使用python manage.py runserver 0.0.0.0:8000
启动项目时,遇到的报错。
查了帖子,有三种解决方式:
- 降低mysqlclient的版本,用1.x的版本,我没试。
- 使用pymysql代替mysqlclient,这个方法可行。
- 分析报错解决问题。
我的报错:
(venv) [root@cs mtb_server]# python manage.py runserver 0.0.0.0:8000
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/opt/mtb/venv/lib/python3.9/site-packages/MySQLdb/__init__.py", line 18, in <module>
from . import _mysql
ImportError: libmysqlclient.so.20: cannot open shared object file: No such file or directory
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/python39/lib/python3.9/threading.py", line 973, in _bootstrap_inner
self.run()
File "/opt/python39/lib/python3.9/threading.py", line 910, in run
self._target(*self._args, **self._kwargs)
File "/opt/mtb/venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "/opt/mtb/venv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run
autoreload.raise_last_exception()
File "/opt/mtb/venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception
raise _exception[1]
File "/opt/mtb/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute
autoreload.check_errors(django.setup)()
File "/opt/mtb/venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "/opt/mtb/venv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/opt/mtb/venv/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate
app_config.import_models()
File "/opt/mtb/venv/lib/python3.9/site-packages/django/apps/config.py", line 301, in import_models
self.models_module = import_module(models_module_name)
File "/opt/python39/lib/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "/opt/mtb/mtb_server/apps/base/models.py", line 4, in <module>
class UserInfo(models.Model):
File "/opt/mtb/venv/lib/python3.9/site-packages/django/db/models/base.py", line 122, in __new__
new_class.add_to_class('_meta', Options(meta, app_label))
File "/opt/mtb/venv/lib/python3.9/site-packages/django/db/models/base.py", line 326, in add_to_class
value.contribute_to_class(cls, name)
File "/opt/mtb/venv/lib/python3.9/site-packages/django/db/models/options.py", line 207, in contribute_to_class
self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
File "/opt/mtb/venv/lib/python3.9/site-packages/django/utils/connection.py", line 15, in __getattr__
return getattr(self._connections[self._alias], item)
File "/opt/mtb/venv/lib/python3.9/site-packages/django/utils/connection.py", line 62, in __getitem__
conn = self.create_connection(alias)
File "/opt/mtb/venv/lib/python3.9/site-packages/django/db/utils.py", line 204, in create_connection
backend = load_backend(db['ENGINE'])
File "/opt/mtb/venv/lib/python3.9/site-packages/django/db/utils.py", line 111, in load_backend
return import_module('%s.base' % backend_name)
File "/opt/python39/lib/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "/opt/mtb/venv/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 15, in <module>
import MySQLdb as Database
File "/opt/mtb/venv/lib/python3.9/site-packages/MySQLdb/__init__.py", line 24, in <module>
version_info, _mysql.version_info, _mysql.__file__
NameError: name '_mysql' is not defined
很明显,我肯定百度了一下,从pypi上看到mysqlclient的解决办法:
sudo yum install python3-devel mysql-devel -y
链接:https://pypi.org/project/mysqlclient/
然后,再执行,还报错......
然后我继续分析报错内容:
Traceback (most recent call last):
File "/opt/mtb/venv/lib/python3.9/site-packages/MySQLdb/__init__.py", line 18, in <module>
from . import _mysql
ImportError: libmysqlclient.so.20: cannot open shared object file: No such file or directory
那就解决这个问题呗,从这个连接上找到了办法,链接:https://www.jianshu.com/p/4e22641c701c
(venv) [root@cs mtb_server]# find / -name "libmysqlclient.so.20"
/opt/software/mysql/lib/libmysqlclient.so.20
(venv) [root@cs mtb_server]# ln -s /opt/software/mysql/lib/libmysqlclient.so.20 /usr/lib64/libmysqlclient.so.20
查找libmysqlclient.so.20
的位置,然后配置软链。
ok了,重新运行可以了。
(venv) [root@cs mtb_server]# python manage.py runserver 0.0.0.0:8000
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 2 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): base.
Run 'python manage.py migrate' to apply them.
June 02, 2022 - 21:33:40
Django version 3.2, using settings 'mtb.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
解决方案2
这个是我在mac m1芯片电脑上遇到的,当时的环境如下:
django4.2 + mysql5.7.31 + mysqlclient2.1.1 + pymsyql1.0.3 + mac m1芯片
在如上的开发环境下,在settings.py中,配置了关于链接MySQL的配置之后,运行项目,Django内部连接MySQL此时用的是mysqlclient模块,但很遗憾报错了如下的错误。
吐槽:mysqlclient安装之后,Django中无需特别的配置即可使用,真是非常方便,但是如果运行报错的话......经过几次解决踩坑经历,我个人推荐改用pymysql模块来代替mysqlclient,因为我试图解决过几次,发现得不偿失,还是pymysql香!
接下来的解决办法就是用的pymysql。
首先就是在项目同级目录下的__init__.py
文件(或者说跟settings.py
文件同级)中,添加如下两行代码。
一般就能直接运行了,如果你配置完能运行,就不用往下看了。
但很不幸,我的Django版本由于是4.x不知道是不是版本太高的问题,导致再次运行的时候,报了如下错误:django.core.exceptions.ImproperlyConfigured: mysqlclient 1.4.3 or newer is required; you have 1.0.3.
遇到报错只能解决了了啊,解决办法,就是在你解释器的安装目录中,修改源码,源码文件所在的位置在你的解释器安装目录中找Lib
或者lib/python/
中的site-packages/django/db/backends/mysql/base.py
文件中的34-37行代码,注释掉即可。
按道理说,上面的源码注释掉,应该就是好了,如果你解决到这里,就能运行了,那就不需要往下看了。
但我继续运行项目,继续报错:django.db.utils.NotSupportedError: MySQL 8 or later is required (found 5.7.31).
好吧,继续找解决办法。
从一篇帖子上找到了解决方式:https://blog.bccn.net/静夜思/68210
那就找找到源码site-packages/django/db/backeds/base/base.py
文件,直接ctrl+f搜索self.check_database_version_supported
,然后把这一行注释掉。
然后,就解决了!!!
SyntaxError: Generator expression must be parenthesized
启动报错:SyntaxError: Generator expression must be parenthesized
,有时候,在使用命令python manager.py runserver
时,会发先启动失败,报错日志如下:
[root@cs es_demo]# python37 manage.py runserver
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f220f0edae8>
Traceback (most recent call last):
File "/usr/local/python/python37/lib/python3.7/site-packages/django/utils/autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "/usr/local/python/python37/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
autoreload.raise_last_exception()
File "/usr/local/python/python37/lib/python3.7/site-packages/django/utils/autoreload.py", line 250, in raise_last_exception
six.reraise(*_exception)
File "/usr/local/python/python37/lib/python3.7/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/usr/local/python/python37/lib/python3.7/site-packages/django/utils/autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "/usr/local/python/python37/lib/python3.7/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/python/python37/lib/python3.7/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/usr/local/python/python37/lib/python3.7/site-packages/django/apps/config.py", line 94, in create
module = import_module(entry)
File "/usr/local/python/python37/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/usr/local/python/python37/lib/python3.7/site-packages/django/contrib/admin/__init__.py", line 4, in <module>
from django.contrib.admin.filters import (
File "/usr/local/python/python37/lib/python3.7/site-packages/django/contrib/admin/filters.py", line 10, in <module>
from django.contrib.admin.options import IncorrectLookupParameters
File "/usr/local/python/python37/lib/python3.7/site-packages/django/contrib/admin/options.py", line 12, in <module>
from django.contrib.admin import helpers, widgets
File "/usr/local/python/python37/lib/python3.7/site-packages/django/contrib/admin/widgets.py", line 151
'%s=%s' % (k, v) for k, v in params.items(),
^
SyntaxError: Generator expression must be parenthesized
可以发现最后一行提示说是语法错误,说是生成器表达式有问题,那具体的报错行内容是'%s=%s' % (k, v) for k, v in params.items(),
,可以看到,最后一个标点符号很有意思,我们找到源码文件对应的行,把这个标点符号去掉即可。
ps:如果是pycharm中修改的话,由于这个文件是源码,还要注意提示框中选择I want to edit this file anyway
。
see also:django1.11 启动错误:Generator expression must be parenthesized
SyntaxError: Generator expression must be parenthesized (widgets.py, line 151)
django1.11 + python3.9
同样是django项目运行时报错:
Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x000001F56FCA28B0>
Traceback (most recent call last):
File "D:\Python\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "D:\Python\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
autoreload.raise_last_exception()
File "D:\Python\lib\site-packages\django\utils\autoreload.py", line 250, in raise_last_exception
six.reraise(*_exception)
File "D:\Python\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "D:\Python\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "D:\Python\lib\site-packages\django\__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "D:\Python\lib\site-packages\django\apps\registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "D:\Python\lib\site-packages\django\apps\config.py", line 94, in create
module = import_module(entry)
File "D:\Python\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 790, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "D:\Python\lib\site-packages\django\contrib\admin\__init__.py", line 4, in <module>
from django.contrib.admin.filters import (
File "D:\Python\lib\site-packages\django\contrib\admin\filters.py", line 10, in <module>
from django.contrib.admin.options import IncorrectLookupParameters
File "D:\Python\lib\site-packages\django\contrib\admin\options.py", line 12, in <module>
from django.contrib.admin import helpers, widgets
SyntaxError: Generator expression must be parenthesized (widgets.py, line 151)
这个报错跟SyntaxError: Generator expression must be parenthesized
报错说的是一回事儿,都是site-packages/django/contrib/admin/widgets.py
文件的151行多了个逗号引起的:
解决办法也简单,删掉逗号就行了。
ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'fault_reporting.userinfo', but app 'fault_reporting' isn't installed.
在新创建的Django项目中执行makemigrations时,遇到:ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'fault_reporting.userinfo', but app 'fault_reporting' isn't installed.
这类我们项目中不存在的app和模型类的错误。
而仔细观察,这个报错的app名字是我们之前某个项目中的app名字,而模型类则是那个app中定义的模型类,但现在却在我们当前的项目中报错了。究其原因,则是因为之前的项目中的app缓存被存在了Django模块内的某些地方
。
而我们当在新的项目中用到"某些地方"的功能时,执行了之前的缓存内容,从而引发错误。而普通的解决办法,就是删除当前项目中的.idea
文件和__pycache__
文件,然后就是删除migrations
目录下的00开头的py文件都解决不了。甚至是卸载Django重新安装————都没用!
因为我们并没有删除Django模块中"某些地方"的缓存文件(pip uninstall Django都清不了这些缓存文件)。so,我们要手动去删除这这个"某个地方"的缓存文件。
打开你的解释器下的Lib\site-packages\django\contrib\admin\migrations
目录,删除除了__init__.py
外的其他的文件。然后再次执行makemigrations
即可。
see also:ValueError in Django when running the “python manage.py migrate” command
RuntimeWarning: DateTimeField Message.date received a naive datetime .....
当在module.py
中定义DateTimeField
类型的字段,在插入记录时:
import time
models.Message.objects.create(
date=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
)
虽然能够保存成功,但会发现一条警告:
C:\Python36\lib\site-packages\django\db\models\fields\__init__.py:1447: RuntimeWarning: DateTimeField Message.date received a naive datetime (2019-06-20 19:51:55) while time zone support is active.
RuntimeWarning)
原因是,Django如果开启了Time Zone功能,则所有的存储和内部处理,甚至包括直接print
显示全都是UTC的。只有通过模板进行表单输入渲染输出的时候,才会执行UTC本地时间的转换。所以我建议后台处理时间的时候,最好完全使用UTC,不要考虑本地时间的存在。而显示时间的时候,也避免手动转换,尽量使用Django模板系统代劳。
解决办法,可以在settings.py
中将USE_TZ
的默认True
改为False
。
USE_TZ = False
TypeError: Object of type 'QuerySet' is not JSON serializable
Django1.11 + Python3.6 + win10
可能的原因
在ROM与ajax交互时,难免会遇到传递queryset对象,但是你会发现使用JsonResponse
并不好用:
from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
def ui_index(request):
if request.method == 'POST':
pk = request.POST.get('pk')
result = ui_models.UiCase.objects.filter(case_vest_project=pk)
# return HttpResponse({"case": result})
return JsonResponse({"case": result}) # 依然不好使
就算使用JsonResponse({"case": result})
依然不好使:
TypeError: Object of type 'QuerySet' is not JSON serializable
可能的解决办法
from django.core import serializers
def ui_index(request):
if request.method == 'POST':
pk = request.POST.get('pk')
result = ui_models.UiCase.objects.filter(case_vest_project=pk)
return JsonResponse({"case": serializers.serialize('json', result)})
这个时候,可以使用serializers
来解决。然后前端的ajax正常接收即可,无需反序列化:
<script>
$(".selected_project").on('click', 'li', function () {
var pk = $(this).attr('pk');
$.ajax({
url: "{% url 'ui_index' %}",
type: "POST",
data: {'pk': pk},
success: function (data) {
console.log(typeof(data), data);
if (data) {
$.each(data, function (index, item) {
console.log(item.case_name, item.pk, )
})
}
}
})
})
</script>
see also:【已解决】Object of type 'QuerySet' is not JSON serializable
TypeError: Object of type Decimal is not JSON serializable
这个跟上面的报错原理一样,json无法序列化Decimal类型的数据,所以,还要加判断,自己处理:
class CustomJsonEncoder(json.JSONEncoder):
def default(self, field):
if isinstance(field, date):
return field.strftime('%Y-%m-%d')
elif isinstance(field, datetime):
return field.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(field, decimal.Decimal):
return float(field)
else:
return json.JSONEncoder.default(self, field)
class Books(View):
def get(self, request):
""" 查 """
books = Book.objects.values('title', 'price')
data_list = json.dumps(list(books), cls=CustomJsonEncoder)
return HttpResponse(data_list, content_type="application/json")
我的表结构是这样的:
from django.db import models
class Book(models.Model):
""" 书籍表 """
title = models.CharField(max_length=32)
price = models.DecimalField(max_digits=8, decimal_places=2) # 999999.99
def __str__(self):
return self.title
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'app01.UserInfo'
这个问题应该是在扩展django auth表时,出现的问题,如下示例:
# settings.py
AUTH_USER_MODEL = "app01.UserInfo"
# app01\models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class UserInfo(AbstractUser): # 必须继承AbstractUser
# 在django默认的user表的基础上添加字段
phone = models.CharField(max_length=11, verbose_name='手机号')
# demo\test.py
import os
import django
from faker import Faker
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings") # demo:项目名称
django.setup()
from django.contrib.auth.models import auth, User
# from django.contrib.auth import get_user_model
# User = get_user_model()
fk = Faker(locale='zh_CN')
def foo():
for i in range(3):
User.objects.create_user(username=fk.name(), password='123', phone=fk.phone_number())
# objs = auth.authenticate(username='王文', password='123')
# print(objs)
if __name__ == '__main__':
foo()
上面的代码运行就会报错:
解决办法就是,当扩展auth表后,你的user对象就不能像原来那样使用了,应该这么用:
import os
import django
from faker import Faker
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings") # demo:项目名称
django.setup()
from django.contrib.auth.models import auth, User
# 导入它
from django.contrib.auth import get_user_model
User = get_user_model() # 用get_user_model返回的User覆盖掉上面的User,其它代码不变
fk = Faker(locale='zh_CN')
def foo():
for i in range(3):
User.objects.create_user(username=fk.name(), password='123', phone=fk.phone_number())
# objs = auth.authenticate(username='王文', password='123')
# print(objs)
if __name__ == '__main__':
foo()
Database returned an invalid datetime value. Are time zone definitions for your database installed?
时区问题:
解决,修改settings.py中的配置:
# 将
USE_TZ = True
# 改为:
USE_TZ = False
参考:
- https://stackoverflow.com/questions/40792628/django-mysql-database-returned-an-invalid-datetime-value
- https://www.codenong.com/cs109366948/
AttributeError: 'str' object has no attribute 'decode'
我在两种情况下遇到这个问题,而且也使用了两种方式进行解决,但后来测了下两种方式应该都可以。这里分别记录下。
情景1
Django2.2 + pymysql1.0.2 + mysql5.7
在Django2.2版本中,配置完毕MySQL的相关配置,重启服务时,发现报错:
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
Exception in thread Thread-1:
Traceback (most recent call last):
File "c:\python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "c:\python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "D:\mydata\demo\all_env\django2.2\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "D:\mydata\demo\all_env\django2.2\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run
self.check_migrations()
File "D:\mydata\demo\all_env\django2.2\lib\site-packages\django\core\management\base.py", line 453, in check_migrations
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
File "D:\mydata\demo\all_env\django2.2\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__
self.loader = MigrationLoader(self.connection)
File "D:\mydata\demo\all_env\django2.2\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__
self.build_graph()
File "D:\mydata\demo\all_env\django2.2\lib\site-packages\django\db\migrations\loader.py", line 212, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "D:\mydata\demo\all_env\django2.2\lib\site-packages\django\db\migrations\recorder.py", line 73, in applied_migrations
if self.has_table():
File "D:\mydata\demo\all_env\django2.2\lib\site-packages\django\db\migrations\recorder.py", line 56, in has_table
return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor())
File "D:\mydata\demo\all_env\django2.2\lib\site-packages\django\db\backends\base\base.py", line 256, in cursor
return self._cursor()
File "D:\mydata\demo\all_env\django2.2\lib\site-packages\django\db\backends\base\base.py", line 233, in _cursor
self.ensure_connection()
File "D:\mydata\demo\all_env\django2.2\lib\site-packages\django\db\backends\base\base.py", line 217, in ensure_connection
self.connect()
File "D:\mydata\demo\all_env\django2.2\lib\site-packages\django\db\backends\base\base.py", line 197, in connect
self.init_connection_state()
File "D:\mydata\demo\all_env\django2.2\lib\site-packages\django\db\backends\mysql\base.py", line 231, in init_connection_state
if self.features.is_sql_auto_is_null_enabled:
File "D:\mydata\demo\all_env\django2.2\lib\site-packages\django\utils\functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\mydata\demo\all_env\django2.2\lib\site-packages\django\db\backends\mysql\features.py", line 82, in is_sql_auto_is_null_enabled
cursor.execute('SELECT @@SQL_AUTO_IS_NULL')
File "D:\mydata\demo\all_env\django2.2\lib\site-packages\django\db\backends\utils.py", line 103, in execute
sql = self.db.ops.last_executed_query(self.cursor, sql, params)
File "D:\mydata\demo\all_env\django2.2\lib\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'
经查,原因是Python安装目录下lib\site-packages\django\db\backends\mysql\operations.py
这个文件中的last_executed_query
方法中的源码写的有问题。
# 第140行开始
def last_executed_query(self, cursor, sql, params):
# With MySQLdb, cursor objects have an (undocumented) "_executed"
# attribute where the exact query sent to the database is saved.
# See MySQLdb/cursors.py in the source distribution.
query = getattr(cursor, '_executed', None)
# 下面的if条件导致报错
if query is not None:
query = query.decode(errors='replace')
return query
解决办法,在GitHub上,最新的Django版本源码中,https://github.com/django/django/blob/master/django/db/backends/mysql/operations.py`,第163-168行,该函数已经被修改为:
这就好办,我们照抄,将我们自己的源码也这么改下:
def last_executed_query(self, cursor, sql, params):
# With MySQLdb, cursor objects have an (undocumented) "_executed"
# attribute where the exact query sent to the database is saved.
# See MySQLdb/cursors.py in the source distribution.
query = getattr(cursor, '_executed', None)
# 修改前的源码
# if query is not None:
# query = query.decode(errors='replace')
# return query
# 修改后的源码
from django.utils.encoding import force_str # 只需要将这个导入,放到该模块的最上面即可
return force_str(query, errors='replace')
然后重启Django就好了。
参考:Django2.2报错::AttributeError: ''str'' object has no attribute ''decode'' | https://github.com/django/django/blob/master/django/db/backends/mysql/operations.py
情景2
python3.9.4 + django2.2 + pymysql1.0.2 + mysql5.7
这次是在Django中配置完了MySQL的相关配置之后,再做makemigrations时,遇到报错了:
xxdeMacBook-Pro:bookcms3 kanghua$ python3.9 manage.py makemigrations
Traceback (most recent call last):
File "/Users/kanghua/PycharmProjects/python-note/study/bookcms3/manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/base.py", line 364, in execute
output = self.handle(*args, **options)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle
loader.check_consistent_history(connection)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/migrations/loader.py", line 283, in check_consistent_history
applied = recorder.applied_migrations()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations
if self.has_table():
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 56, in has_table
return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor())
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/base/base.py", line 256, in cursor
return self._cursor()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/base/base.py", line 233, in _cursor
self.ensure_connection()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection
self.connect()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/base/base.py", line 197, in connect
self.init_connection_state()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 231, in init_connection_state
if self.features.is_sql_auto_is_null_enabled:
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/mysql/features.py", line 82, in is_sql_auto_is_null_enabled
cursor.execute('SELECT @@SQL_AUTO_IS_NULL')
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/utils.py", line 103, in execute
sql = self.db.ops.last_executed_query(self.cursor, sql, params)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/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'
然后,搞笑的是,我忘记了曾经解决过这个问题了,就又去百度搜的......
先说解决方案,按照报错的最后一行提示lib/python3.9/site-packages/django/db/backends/mysql/operations.py
这个源码文件的146行报错了,那就改吧:
完事之后,重新做数据库迁移,应该就可以了:
xxdeMacBook-Pro:bookcms3 kanghua$ python3.9 manage.py makemigrations
Migrations for 'book':
book/migrations/0001_initial.py
- Create model Author
- Create model Publish
- Create model Book
感觉要比情景一中的解决要简单啊!最后,没啥说的,用哪种解决方式都行,只要能解决问题的方案就是好方案!
参考:Django+MySQL+python报错:AttributeError: ‘str‘ object has no attribute ‘decode‘
UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6 in position 9737: illegal multibyte sequence
Django2.2 + Python3.6.8
在Django2.2和django3版本中,如果访问页面,后台报:
UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6 in position 9737: illegal multibyte sequence
这种情况是源码存在读文件编码没有设置的问题,根据报错的历史回溯发现,在你的*lib\site-packages\django\views\debug.py
这个文件的331行有问题:
修改前:
修改后:
现在就可以正常的访问了。
参考:https://blog.csdn.net/qq_37232731/article/details/89684409
ValueError: source code string cannot contain null bytes
django项目中,报这个错误时,第一怀疑对象是各个py
文件的编码格式不一样导致的,请检查并将所有文件的编码保持一致,推荐使用utf-8编码。
如果你用的是pycharm,File→Settings→Editor→File Encodings,修改Project Encoding和Properties Files都为UTF-8编码格式就完了。
"block" tag with name "device_list_class" appears more than once
这个报错指的是,在一个模板中(一个html页面中)不能同时定义多个同名的block块。
来自官网的解释:Finally, note that you can’t define multiple block tags with the same name in the same template. This limitation exists because a block tag works in “both” directions. That is, a block tag doesn’t just provide a hole to fill – it also defines the content that fills the hole in the parent. If there were two similarly-named block tags in a template, that template’s parent wouldn’t know which one of the blocks’ content to use.
TypeError: isinstance() arg 2 must be a type or tuple of types
win10 + django3.2
注意,这个错误本身是个外键字段to后的模型类需不需要带引号的问题,但是报错却不太一样。
当前这个报错是我扩展auth_user表时,做外键关联时,发生的问题。如果不是扩展auth_user表,则是另外的报错参考本篇app02.UserInfo.stu: (fields.E300) Field defines a relation with model 'Student', which is either not installed, or is abstract. app02.UserInfo.stu: (fields.E307) The field app02.UserInfo.stu was declared with a lazy reference to 'app02.student', but app 'app02' do esn't provide model 'student'.
部分。
先来看扩展auth_user表时,遇到的报错,也就是TypeError: isinstance() arg 2 must be a type or tuple of types
报错。
我们说,绑定外键,你可以:
from django.db import models
from django.contrib.auth.models import AbstractUser # 别忘了导入
class UserDetail(models.Model):
phone = models.CharField(max_length=11, verbose_name='手机号', default='')
class UserInfo(AbstractUser): # 必须继承这个AbstractUser类
# to后面的类,可以带引号或者不带引号
# detail = models.OneToOneField(to="UserDetail", on_delete=models.CASCADE)
detail = models.OneToOneField(to=UserDetail, on_delete=models.CASCADE)
def __str__(self):
return self.username
这样,你做数据库迁移的时候,不报错,但是,注意!!!这是有前提的,这要外键关联的表也在同一个models中。
如果你外键关联表再别的models中,你就不能使用带引号的形式了:
from django.db import models
from django.contrib.auth.models import AbstractUser # 别忘了导入
from app02.models import Student # 另一个app中的Student模型类
class UserDetail(models.Model):
phone = models.CharField(max_length=11, verbose_name='手机号', default='')
class UserInfo(AbstractUser): # 必须继承这个AbstractUser类
# 外键关联模型类,在同一个models中,to后面的类,可以带引号或者不带引号
# 带引号的话,默认在当前models中找,我们的UserDetail正好符合条件,所以没问题
detail = models.OneToOneField(to=UserDetail, on_delete=models.CASCADE)
# 注意,如果外键关联的模型类,在另一个models中,如下面的stu字段,关联的模型类在另一个app的models中
# to后面的模型类,带引号的话,数据库迁移时,就会报错:TypeError: isinstance() arg 2 must be a type or tuple of types
# 那就不能带引号了
# stu = models.OneToOneField(to='Student', on_delete=models.CASCADE) # 数据库迁移报错
stu = models.OneToOneField(to=Student, on_delete=models.CASCADE) # 数据库迁移不报错
def __str__(self):
return self.username
参考:https://blog.csdn.net/weixin_30639719/article/details/99091219
app02.UserInfo.stu: (fields.E300) Field defines a relation with model 'Student', which is either not installed, or is abstract.
win10 + django3.2
这个报错跟本篇TypeError: isinstance() arg 2 must be a type or tuple of types
这个报错,其实说的是一个问题,报本小节这个错误,就是普通的外键关联模型类时,指定to后面的模型类加了引号,导致的。
首先app01.models.py
:
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=32)
然后app02.models
中引入了app01的student模型类,然后......由于引号引发的报错:
from django.db import models
from app01.models import Student
class UserDetail(models.Model):
phone = models.CharField(max_length=11, verbose_name='手机号', default='')
class UserInfo(models.Model):
# 外键关联模型类,在同一个models中,to后面的类,可以带引号或者不带引号
# 带引号的话,默认在当前models中找,我们的UserDetail正好符合条件,所以没问题
detail = models.OneToOneField(to=UserDetail, on_delete=models.CASCADE)
# 注意,如果外键关联的模型类,在另一个models中,如下面的stu字段,关联的模型类在另一个app的models中
# to后面的模型类,带引号的话,数据库迁移时,就会报错
# 那就不能带引号了
# stu = models.OneToOneField(to='Student', on_delete=models.CASCADE) # 数据库迁移报错
stu = models.OneToOneField(to=Student, on_delete=models.CASCADE) # 数据库迁移不报错
加引号报错:
(base) D:\downloads\demo>python manage.py makemigrations
SystemCheckError: System check identified some issues:
ERRORS:
app02.UserInfo.stu: (fields.E300) Field defines a relation with model 'Student', which is either not installed, or is abstract.
app02.UserInfo.stu: (fields.E307) The field app02.UserInfo.stu was declared with a lazy reference to 'app02.student', but app 'app02' do
esn't provide model 'student'.
binascii.Error: Invalid base64-encoded string: number of data characters (221) cannot be 1 more than a multiple of 4
django1.11
这个报错挺奇妙的,访问admin页面报错:
Internal Server Error: /admin/
Traceback (most recent call last):
File "D:\env\env2\lib\site-packages\django\contrib\sessions\backends\base.py", line 202, in _get_session
return self._session_cache
AttributeError: 'SessionStore' object has no attribute '_session_cache'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\env\env2\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
response = get_response(request)
File "D:\env\env2\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "D:\env\env2\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\env\env2\lib\site-packages\django\contrib\admin\sites.py", line 242, in wrapper
return self.admin_view(view, cacheable)(*args, **kwargs)
File "D:\env\env2\lib\site-packages\django\utils\decorators.py", line 149, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "D:\env\env2\lib\site-packages\django\views\decorators\cache.py", line 57, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "D:\env\env2\lib\site-packages\django\contrib\admin\sites.py", line 213, in inner
if not self.has_permission(request):
File "D:\env\env2\lib\site-packages\django\contrib\admin\sites.py", line 187, in has_permission
return request.user.is_active and request.user.is_staff
File "D:\env\env2\lib\site-packages\django\utils\functional.py", line 238, in inner
self._setup()
File "D:\env\env2\lib\site-packages\django\utils\functional.py", line 385, in _setup
self._wrapped = self._setupfunc()
File "D:\env\env2\lib\site-packages\django\contrib\auth\middleware.py", line 24, in <lambda>
request.user = SimpleLazyObject(lambda: get_user(request))
File "D:\env\env2\lib\site-packages\django\contrib\auth\middleware.py", line 12, in get_user
request._cached_user = auth.get_user(request)
File "D:\env\env2\lib\site-packages\django\contrib\auth\__init__.py", line 210, in get_user
user_id = _get_user_session_key(request)
File "D:\env\env2\lib\site-packages\django\contrib\auth\__init__.py", line 61, in _get_user_session_key
return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY])
File "D:\env\env2\lib\site-packages\django\contrib\sessions\backends\base.py", line 57, in __getitem__
return self._session[key]
File "D:\env\env2\lib\site-packages\django\contrib\sessions\backends\base.py", line 207, in _get_session
self._session_cache = self.load()
File "D:\env\env2\lib\site-packages\django\contrib\sessions\backends\db.py", line 37, in load
return self.decode(s.session_data)
File "D:\env\env2\lib\site-packages\django\contrib\sessions\backends\base.py", line 103, in decode
encoded_data = base64.b64decode(force_bytes(session_data))
File "c:\users\26217\appdata\local\programs\python\python39\lib\base64.py", line 87, in b64decode
return binascii.a2b_base64(s)
binascii.Error: Invalid base64-encoded string: number of data characters (221) cannot be 1 more than a multiple of 4
[05/May/2022 15:19:44] "GET /admin/ HTTP/1.1" 500 134139
[05/May/2022 15:21:00] "GET /admin/ HTTP/1.1" 302 0
[05/May/2022 15:21:00] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1650
通过观察报错内容发现两个重要的报错信息:
AttributeError: 'SessionStore' object has no attribute '_session_cache'
binascii.Error: Invalid base64-encoded string: number of data characters (221) cannot be 1 more than a multiple of 4
发现报错跟session有关,那么解决办法首先尝试:
- 重新做数据库迁移命令,未解决!
- 检查django内置session表,是否有内容,如果的话选择手动清空session表记录,然后再重新访问发现就好了。
that's all, see also:
'staticfiles' is not a registered tag library.Must be one of:
django3.2
这个报错应该是使用django3运行django1版本开发的项目,报错截图:
而django3的官档对此作了说明,移除了staticfiles
官档链接:https://docs.djangoproject.com/en/dev/releases/3.0/#features-removed-in-3-0
那解决办法也好办,就是将{% load staticfiels %}
改为{% load static %}
。
或者参考StackOverflow:https://stackoverflow.com/questions/55929472/django-templatesyntaxerror-staticfiles-is-not-a-registered-tag-library,配置settings。
django.db.utils.IntegrityError: NOT NULL constraint failed: django_admin_log.user_id
win10 + python3.9 + django1.11 + sqlite3
法1
数据库执行makemigrations
成功,执行migrate
报错django.db.utils.IntegrityError: NOT NULL constraint failed: django_admin_log.user_id
,这是外键约束的错误。
想了想这是从别的地方拿来的项目,数据都有,就是拿过来之后,执行数据库迁移报错了。
解决办法,就是找到sLib\site-packages\django\contrib\admin\migrations
目录,将其内的000
开头的py文件都删掉,然后重新执行数据库迁移命令就可以了。
法2
方法1要是不灵,那肯定是你模型类的外键定义的问题了,即外键字段需要传值,你添加数据的时候没有传,导致的报错。
但就是不想传值咋办?好办,添加一个null=True
属性,然后重新执行数据库迁移那两条命令,应该就好了。
让外键字段可以为空。
AttributeError: 'AdminSite' object has no attribute '_registry'
django1.11
这是个非常神奇的错误,我原本用的是django1.11版本,然后就创建好项目之后,启动报这个错,怎么都没排出来.....
原谅我太菜!!!
后来,我就把django1.11卸载了!换了django1.11.29版本(django1.x的最后一个版本了)。
然后就好了。
UnboundLocalError: local variable 'before_import_registry' referenced before assignment
django1.11
这是个非常神奇的错误,跟解决AttributeError: 'AdminSite' object has no attribute '_registry'
报错时遇到的,我原本用的是django1.11版本,然后就创建好项目之后,启动报这个错,怎么都没排出来.....
原谅我太菜!!!
后来,我就把django1.11卸载了!换了django1.11.29版本(django1.x的最后一个版本了)。
然后就好了。
RuntimeError: 'cryptography' package is required for sha256_password or caching_sha2_password auth methods
django3.2 + mysql8.0
项目中配置了mysql之后,运行报错:
RuntimeError: 'cryptography' package is required for sha256_password or caching_sha2_password auth methods
解决办法就是,下载cryptography
模块:
pip install cryptography
ModuleNotFoundError: No module named 'tencentcloud'
报这个错,一般是在使用腾讯云短信时忘了下载对应的模块了,解决办法就是下载这个模块就好了:
pip install --upgrade tencentcloud-sdk-python