Django使用URL参数在基于类的视图中查询数据库

时间:2018-10-10 01:14:38

标签: django django-class-based-views url-parameters

我有一个表单,提交后会转到其中的URL例如:

appname/results/?make=BMW

我想使用URL参数查询数据库并在该页面上显示结果。

这是我到目前为止的代码:

观看次数

class SearchView(FormView):

    template_name = 'carproject/search.html'

    def get(self, request, *args, **kwargs):
        form = AdvancedSearch(self.request.GET or None)
        context = {'form': form}
        if form.is_valid():
            return render(request, 'carproject/results.html')
        else:
            return render(request, self.template_name, context)

class ResultsView(TemplateView):
    template_name = 'carproject/results.html'

    def get_queryset(self, request, *args, **kwargs):
        make = self.request.GET.get('make')
        results = Vehicles.objects.filter(makename__icontains='make')
        context = {'results': results}

        return render(request, self.template_name, context)

HTML

<table>
{% for item in results%}
                <tr>
                    <td>{{item.makename}}</td>
                    <td>{{item.model}}</td>
                    <td>{{item.seriesname}}</td>
                    <td>{{item.seatingcapacity}}</td>
                    <td>{{item.pricenew}}</td>
                </tr>
                {% endfor %}
</table>

1 个答案:

答案 0 :(得分:0)

我不知道问题是什么,但是您应该更改

results = Vehicles.objects.filter(makename__icontains='make')

results = Vehicles.objects.filter(makename__icontains=make)

'make'-> make