我在 Django 中有一个简单的博客代码,我写了错误和我的代码:
有我的代码 模型.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(
'auth.User',
on_delete=models.CASCADE,
)
body = models.TextField()
def __str__(self):
return self.title
views.py
from django.views.generic import ListView
from .models import Post
class BlogListView(ListView):
model = Post
template_name = 'home.html'
urls.py
from django.urls import path
from .views import BlogListView
urlpatterns = [
path('', BlogListView.as_view(), name= 'home')
]
和 home.html
{% extends 'base.html' %}
{% block content %}
{% for post in object_list %}
<div class="post-entry">
<h2><a href="">{{ post.title }}</a></h2>
<p>{{ post.body }}</p>
</div>
{% endfor %}
{% endblock content %}
运行代码后出现错误信息:
AttributeError at /admin/blog/post
'list' object has no attribute 'lower'
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/blog/post
Django Version: 3.1.5
Exception Type: AttributeError
Exception Value:
'list' object has no attribute 'lower'
Exception Location: C:\Users\nilaroz\.virtualenvs\blog-Keg_c4F1\lib\site-packages\django\utils\http.py, line 295, in is_same_domain
Python Executable: C:\Users\nilaroz\.virtualenvs\blog-Keg_c4F1\Scripts\python.exe
Python Version: 3.8.6
Python Path:
['D:\\MyDjangoProject\\blog',
'c:\\program files (x86)\\python38-32\\python38.zip',
'c:\\program files (x86)\\python38-32\\DLLs',
'c:\\program files (x86)\\python38-32\\lib',
'c:\\program files (x86)\\python38-32',
'C:\\Users\\nilaroz\\.virtualenvs\\blog-Keg_c4F1',
'C:\\Users\\nilaroz\\.virtualenvs\\blog-Keg_c4F1\\lib\\site-packages']
Server time: Sun, 31 Jan 2021 19:53:08 +0000
为什么?我不做任何清单! “'list' 对象没有属性 'lower'”是什么意思? 我想也许 Django 在调用 for 循环时会列出一个列表!
{% for post in object_list %}
我如何解决这个问题?
答案 0 :(得分:0)
我找到了解决办法: 我写错了
'DIRS': [str(BASE_DIR.joinpath('templates'))],
在
ALLOWED_HOSTS = []
while 应该写在 "TEMPLATES" 的 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': [str(BASE_DIR.joinpath('templates'))],
},
]
我建议不要在很累的时候编码。睡觉!