运行Django DetailView时出现属性错误


class results(DetailView):
model = Location
template_name = 'results.html'
def get_object(self, **kwargs):
context = super(results, self).get_context_data(**kwargs)
query = self.request.GET.get('q')
context.update({
'location': Location.objects.filter(name__icontains=query)
})
return context

上述函数的目的是获取用户的输入字符串,并在过滤后将其显示在DetailView中。然而,当我运行它时,会生成以下错误消息:

AttributeError at /collector/results/
'results' object has no attribute 'object'
Request Method: GET
Request URL:    http://127.0.0.1:8000/collector/results/?q=Hong+Kong
Django Version: 3.1.7
Exception Type: AttributeError
Exception Value:    
'results' object has no attribute 'object'

有人知道是什么原因导致错误,以及如何修复代码吗?

小心您要覆盖的内容,您要覆盖get_context_data而不是get_object:

def get_context_data(self, **kwargs):
context = super(results, self).get_context_data(**kwargs)
query = self.request.GET.get('q')
context.update({
'location': Location.objects.filter(name__icontains=query)
})
return context

最新更新