我正在尝试在Django中实现一个简单的搜索功能,但是以某种方式我无法将参数从模板传递给视图功能。我遇到了一个关键错误:/ artdb / search /处出现KeyError,因为kwargs为空:
url.py:
path('search/',views.Search.as_view(),name='search'),
base,.html:
<form class="form-inline my-2 my-lg-0" name="search" action="{% url 'artdb:search' %}" {{ form.as_p }} method="get">{% csrf_token %}
<input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search" value="{{seastr}}">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit" value="{{seastr}}">Search</button>
</form>
views.py:
class Search(ListView):
print("class Search")
model=Person
template_name='artdb/search.html'
context_object_name='ans'
def get_queryset(self):
Pdb().set_trace()
self.seastr=get_object_or_404(Person,name=self.kwargs['seastr'])
return Person.objects.filter(seastr=self.seastr)
答案 0 :(得分:1)
您没有在seastr
字段中附加名称<input>
:
<form class="form-inline my-2 my-lg-0" name="search" action="{% url 'artdb:search' %}" {{ form.as_p }} method="get">{% csrf_token %}
<input name="seastr" class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search" value="{{seastr}}">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
请注意name="seastr"
标签中的<input>
。
GET参数不是存储在self.kwargs
中,而是存储在self.request.GET
中,因此我们可以使用self.request.GET['seastr']
获取该参数。
通常带有搜索栏的页面与带有请求栏的页面相同,因此搜索请求(经常是可选)。因此,在此处将过滤设置为可选可能会很有用:
class Search(ListView):
model=Person
template_name='artdb/search.html'
context_object_name='ans'
def get_queryset(self):
q = self.request.GET.get('seastr')
if q is not None:
return Person.objects.filter(seastr=q)
else:
return Person.objects.all()
最后请注意,seastr
参数不是上下文数据的一部分。您可以通过打补丁来使这部分内容成为上下文数据:
class Search(ListView):
model=Person
template_name='artdb/search.html'
context_object_name='ans'
def get_queryset(self):
q = self.request.GET.get('seastr')
if q is not None:
return Person.objects.filter(seastr=q)
else:
return Person.objects.all()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['seastr'] = self.request.GET.get('seastr')
return context