
本文共 2714 字,大约阅读时间需要 9 分钟。
Django报错整理
持续更新中······
文章目录
AttributeError
- AttributeError: ‘WSGIRequest’ object has no attribute ‘post’
发现问题出在语句
request.post
解决方案
request只有POST而不是post,修改成以下语句即可
request.POST
ImportError
- ImportError: cannot import name ‘render_to_response’
from django.shortcuts import render_to_response
在使用render_to_response时,抛出的错误。经查询发现django3.0已经将render_to_response移除了,也就是说只有2.x以下的版本才能用render_to_response,3.0以后就不能用了。
解决方案一
卸载3.0版本,使用2.x版本
python -m pip uninstall djangopython -m pip install djnago==2.1.3
解决方案二
用3.0版本中的render代替render_to_response
TemplateDoesNotExist
已经在根目录下创建了template文件夹,并添加了index.html,但是runserver时报错TemplateDoesNotExist。这是因为没有将template添加到settings.py的路径中。
解决方案
在settings.py中找到
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', ], }, },]
在DIRS后添加
'DIRS': [os.path.join(BASE_DIR, 'templates')],
TypeError
- TypeError: context must be a dict rather than Context.
这个错误出现在
t = loader.get_template('xls.html') c = Context({ 'data': address, }) response.write(t.render(c))
原因是在我所用的django2.1.3中render的参数不支持Context对象,只能以字典的形式传入,否则就会出现上文的报错。
解决方案
将Context对象修改成字典对象,即可正常运行
t = loader.get_template('xls.html') c = { 'data': address, } response.write(t.render(c))
OptionalError
- OptionalError ast /admin/address/address/add/
用超级用户创建用户时,save时抛出错误:
no such table:main.auth_user__old
- 更新django
- 删除原数据库文件
- 迁移数据库
一、更新django
google后发现是版本的问题,将django更新到2.1.7即可:python -m pip --upgrade django==2.1.7
二、删除原数据库文件
将app目录下的migrations文件夹和项目根目录下的db.sqlite3删去。
重启环境! 我之前没有重启环境就直接在此迁移数据库,后来runserver时发现原来设置的超级用户信息竟然还在,当然再次失败。三、迁移数据库
依次执行以下三步:
python manage.py migratepython manage.py migrate app_namepython manage.py migrations app_name
成功解决。

TemplateSyntaxError
- TemplateSyntaxError at /change_gender/
TemplateSyntaxError at /change_gender/'admin_tags' is not a registered tag library. Must be one of:admin_listadmin_modifyadmin_staticadmin_urlscachecustom_tagsi18nkingadmin_tagsl10nlogstaticstaticfilestz
这种报错一般是templatetags没有放在app下,而放在项目根目录下了。
解决方法
方法一:
将templatetags放在app目录下 方法二: 在settings.py中的option栏目下添加'libraries':{ 'my_tags': 'app_name.templatetags.my_tags', }
成功解决。
ModuleNotFoundError: No module named ‘django.templates’
这个报错是我在把template目录refactor成templates之后发生的错误。
解决方法
原因是settings文件也被refactor了,所以点击File->Local History->Show History将settings文件修改成refactor之前的版本就好了。
发表评论
最新留言
关于作者
