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

Django通用视图创建投票应用报错:polls.views无IndexView属性

解决Django通用视图AttributeError问题

错误原因

你在urls.py中引用了views.IndexView、views.DetailView、views.ResultsView类视图,但polls/views.py文件中未定义这些类,导致Django无法找到对应属性,抛出AttributeError。

解决步骤

修改polls/views.py文件,导入Django通用视图基类并定义所需的类视图:

  1. 先导入必要模块:
from django.views.generic import ListView, DetailView
from .models import Question
  1. 定义三个类视图:
class IndexView(ListView):
    # 覆盖默认模板路径,指定自定义模板
    template_name = 'polls/index.html'
    # 覆盖默认上下文变量名,匹配模板中使用的变量
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """返回最近发布的5个问题"""
        return Question.objects.order_by('-pub_date')[:5]

class DetailView(DetailView):
    model = Question
    template_name = 'polls/detail.html'

class ResultsView(DetailView):
    model = Question
    template_name = 'polls/results.html'

注意事项

  • 确保views.py中的类名与urls.py引用的完全一致(大小写、拼写不能出错)
  • 确认已在polls/templates/polls/目录下创建对应的模板文件(index.html、detail.html、results.html)
  • 若之前写过函数式的index、detail、results视图,需替换为上述类视图,或删除urls.py中对应的类视图引用(当前方案建议保留类视图实现)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 23:15:16