Skip to main content
 首页 » 编程设计

python之Django之在类通用 View 中出现语法错误

2024年12月31日19JeffreyZhao

现在我正在学习 Django 并浏览文档。当我尝试使用通用 View 时,它给了我一个异常(exception):

  File "/home/jeffr/Рабочий стол/codetry/mysite1/polls/views.py", line 8 
     def IndexView(generic.ListView): 
                          ^ 
  SyntaxError: invalid syntax 

这是我的views.py:

    from django.views import generic 
 
    from .models import Choice, Question 
 
    def IndexView(generic.ListView): 
        template_name = 'polls/index.html' 
         contest_object_name = 'latest_question_list' 
 
    get_queryset(self): 
        """Return the last five published questions""" 
        return Question.objects.order_by('-pub_date')[:5] 
 
    def DetailView(generic.DetailView): 
        model = Question 
        template_name = 'polls/detail.html' 

可以在此处找到完整的追溯粘贴:http://dpaste.com/3QMN3A0

非常感谢任何帮助,谢谢

请您参考如下方法:

def 关键字表示您正在实现一个函数。但是这里您没有指定一个函数,而是一个类。您使用 class 关键字定义一个类,例如:

from django.views import generic 
 
from .models import Choice, Question 
 
<b>class</b> IndexView(generic.ListView): 
    template_name = 'polls/index.html' 
     contest_object_name = 'latest_question_list' 
 
    <b>def</b> get_queryset(self): 
        """Return the last five published questions""" 
        return Question.objects.order_by('-pub_date')[:5] 
 
<b>class</b> DetailView(generic.DetailView): 
    model = Question 
    template_name = 'polls/detail.html'

这会引发错误,因为函数可以接受参数,但参数名称不能包含点。

您还忘记了使用 def 来定义 get_queryset 方法。