跟着入门教程一步步敲代码,踩了几个坑记录以下
1、template invalid block tag
在调用template时提示template格式不对KeyError: 'endfor', invalid_block_tag, Invalid block tag on line 22,网上找了一下是模板中百分号和花括号不能有空格,否则识别错误。去掉标签后提示消失。
Traceback (most recent call last):
File "D:\Python36\lib\site-packages\django\template\base.py", line 470, in par
se
compile_func = self.tags[command]
KeyError: 'endfor'
File "D:\Python36\lib\site-packages\django\template\base.py", line 534, in inv
alid_block_tag
"or load this tag?" % (token.lineno, command)
django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 22: 'e
ndfor'. Did you forget to register or load this tag?
{% for question in latest_question_list %}
<li><a href = "/polls/{
{question.id}}/"> {
{ question.question_text}} </a></li>
{% endfor %}
2、template路径配置
render调用模板的时候提示TemplateDoesNotExist,需要配置setting.py文件中的TEMPLATES,通过DIRS指定模板路径。
由startproject命令生成的settings.py定义关于模板的值:
- DIRS定义了一个目录列表,模板引擎按列表顺序搜索这些目录以查找模板源文件
- APP_DIRS告诉模板引擎是否应该在每个已安装的应用中查找模板
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,"/polls/templates")],
'APP_DIRS': True,
File "D:\Python36\lib\site-packages\django\template\loader.py", line 19, in ge
t_template
raise TemplateDoesNotExist(template_name, chain=chain)
django.template.exceptions.TemplateDoesNotExist: templates/pollindex.html
3、编码问题
有时候提示UnicodeDecodeError,尝试了下列修改,不确定是否解决了问题。
UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6 in position 9737: illegal
multibyte sequence
1、确保views页面首行设置了默认编码 # -*-coding:utf-8 -*-
2、确保html页面的编码为 utf-8,UltraEdit另存为的时候选择格式为UTF-8不带BOM。
BOM——Byte Order Mark,就是字节序标记
是否带BOM按照下文介绍选择不带BOM。
https://blog.csdn.net/change_any_time/article/details/79572370
3、确保项目setting文件设置了
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
4、在项目setting文件中设置
DEFAULT_CHARSET = 'utf-8'
4、CBV模式
将view改为class后各种错误提示
后来发现一是as_View后面要加双括号,二是view里面定义的class不能与预定义的View同名。
TypeError: as_view() takes 1 positional argument but 2 were given
path("<int:pk>", views.DetailView.as_View(), name = 'detail'),AttributeError: type object 'DetailView' has no attribute 'as_View' super().execute(*args, **options)
5、定制Admin后台模板
修改admin后台模板后runserver启动失败,后来发现将fieldsets和list_display的执行顺序调换即可正常。
先覆盖list_display后覆盖fieldsets。
IndentationError: unindent does not match any outer indentation level (admin.py,
line 16)
class QuestionAdmin(admin.ModelAdmin):
list_display = ('question_text', 'pub_date', 'was_pub_recently')
fieldsets = [
(None, { 'fields' : ['question_text']}),
('Date Information', { 'fields' : ['pub_date']}),
]
inlines = [ ChoiceInline ]