You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django类视图报错'function' object has no attribute 'as_view'

报错原因

抛出AttributeError: 'function' object has no attribute 'as_view'是因为你将Django基于类的视图错误定义成了函数,函数对象不存在类视图专属的as_view()方法,调用时自然报错。
你的代码存在两处核心错误:

  • 定义PostListView时错用了函数定义关键字def,类视图需要用class关键字定义,才能正确继承ListView通用类的属性和方法。你当前写法里的ListView被识别为函数的形参,完全没有触发类继承逻辑。
  • views.py头部导入语句语法错误,from re import template import django是无效导入,和当前视图逻辑无关的冗余导入可以直接删除。

修正方案

修正后的views.py

from django.shortcuts import render
from django.views.generic import ListView
from .models import Post

# 用class关键字定义类视图,继承ListView
class PostListView(ListView):
    model = Post
    template_name = 'blog/home.html'
    context_object_name = 'posts'
    ordering = ['-date_posted']

# 补充about函数视图,匹配urls里的路由配置
def about(request):
    return render(request, 'blog/about.html', {'title': 'About'})

修正后的urls.py

整理冗余导入,写法更简洁:

from django.urls import path
from .views import PostListView, about

urlpatterns = [
    path('', PostListView.as_view(), name="blog-home"),
    path('about/', about, name="blog-about"),
]

补充说明:改完代码后如果仍有异常,优先检查blog/home.html模板路径是否正确、Post模型是否存在date_posted字段即可。


内容的提问来源于stack exchange,提问作者Kundan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 02:30:55