python - Django 要求定义 `model`,而它已经定义了

标签 python django

我已经在我的 View 中定义了 model = Post。但仍然要求定义模型或查询集!那我哪里做错了?

View .py

from .models import Post
from django.views.generic import ListView
# Create your views here.
class PostList(ListView):
    model = Post
    template_name = 'home.html'

url.py

from django.urls import path
from . import views
urlpatterns = [
    path('',views.ListView.as_view(),name ='list')
]

回溯错误

File "D:\django\blog_env\lib\site-packages\django\core\handlers\exception.py" in inner
  35.             response = get_response(request)

File "D:\django\blog_env\lib\site-packages\django\core\handlers\base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "D:\django\blog_env\lib\site-packages\django\core\handlers\base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "D:\django\blog_env\lib\site-packages\django\views\generic\base.py" in view
  69.             return self.dispatch(request, *args, **kwargs)

File "D:\django\blog_env\lib\site-packages\django\views\generic\base.py" in dispatch
  89.         return handler(request, *args, **kwargs)

File "D:\django\blog_env\lib\site-packages\django\views\generic\list.py" in get
  142.         self.object_list = self.get_queryset()

File "D:\django\blog_env\lib\site-packages\django\views\generic\list.py" in get_queryset
  39.                     'cls': self.__class__.__name__

Exception Type: ImproperlyConfigured at /
Exception Value: ListView is missing a QuerySet. Define ListView.model, ListView.queryset, or override ListView.get_queryset().

最佳答案

您定义了一个 PostList View 类,但忘记使用该基于类的 View ,而是使用了 ListView 父类。因此,您需要替换:

from django.urls import path
from . import views
urlpatterns = [
    path('',<s>views.ListView.as_view()</s>,name ='list')
]

与:

from django.urls import path
from . import views
urlpatterns = [
    path('', views.<b>PostList</b>.as_view(),name ='list')
]

否则 Django 将使用 ListView 类,并且该类(故意)缺少 modelqueryset 属性,因为这个想法是在真实(非抽象)基于类的 View 级别指定它。

关于python - Django 要求定义 `model`,而它已经定义了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51385047/

相关文章:

python - 如何删除numpy中具有相同值的列

python - 即使使用当前 python 版本安装 Numpy 导入错误

python - 如何在 OS X 10.10.3 中卸载和/或管理多个版本的 python

django - tastypie 显示原始外键 id 值

python - 删除 PIP 中所有已失效依赖者的包

database - 如何处理这个错误 (1049, "Unknown database '/users/ohyunjun/work/astral/mysql'")

python - 如何为卷积神经网络的可变输入大小添加扁平层(或类似层)

python - 在命令行中 cap.isOpened() 时返回状态

python - 测试 post API 接收状态代码 200 而不是 201

Python - 拆分由空格和逗号分隔的名称字符串