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

标签 python django view syntax

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

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

这是我的观点.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 方法。

关于python - Django - 在类通用 View 中出现语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54046538/

相关文章:

python - 如何从 Django 中的请求 QueryDict 中删除 key ?

sql - 用于聚合数据的物化 View 与触发器?

ios - 点击后隐藏 View

python - tensorflow 中大型稀疏矩阵的特征向量

python - 计算文件中的每个字符

python pprint嵌套字典换行符每个嵌套?

ios - swift:重新加载 View 以在图表中显示新数据

python - 如何将不同的模型添加到 ModelForm 作为额外字段?

python - NoReverseMatch 在/accounts/signup/django-allauth 错误

python - 如何对整个 python 项目进行分析?