运行 Django DetailView 时出现属性错误

时间:2021-03-22 12:05:49

标签: django django-templates

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'

有谁知道导致错误的原因,以及如何修复代码?

1 个答案:

答案 0 :(得分:1)

小心你覆盖的内容,你想覆盖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