python - Django - 在类通用视图中出现语法错误
问题描述
现在我正在学习 django 并浏览文档。当我尝试使用通用视图时,它给了我一个例外:
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
class IndexView(generic.ListView):
template_name = 'polls/index.html'
contest_object_name = 'latest_question_list'
def get_queryset(self):
"""Return the last five published questions"""
return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
这会引发错误,因为函数可以接受参数,但参数名称不能包含点。
您还忘记了使用 adef
来定义get_queryset
方法。
推荐阅读
- python - 循环遍历电子邮件以将附件提取到多个位置
- php - 教义最大子串
- python - 在 Python 中将字典转换为 DataFrame - 3 个键和 1 个值深度
- python - 如何从 CSV 文件创建字典
- php - 使用数组验证值,Laravel 验证。数组中的值必须为 1
- html - Angular 类 ng-star-inserted 覆盖我的类
- javascript - 有没有办法将画布分成两部分?
- json - Azure - 创建具有多个值的标记并使用 json 将其应用于资源组
- php - PayPal PayPalCheckoutSdk 获取付款人的账单地址
- python - unittest 自动模拟而无需分配