如果数据库中存在搜索项,我正在尝试在Django中实现搜索栏。但是其显示查询返回None值。我是django的新手,请帮助我
views.py
def search(request):
if request.method == 'GET':
form = LocForm(request.POST)
if form.is_valid():
search_query = request.GET.get('search_box', None)
print(search_query)
FirstLoc_list_obj = FirstLoc_List.objects.filter(address__icontains=search_query)
SecondLoc_list_obj= SecondLoc_list.objects.filter(address__icontains=search_query)
if (len(FirstLoc_list_obj) or len(SecondLoc_list_obj)) > 0:
print("Locaton Found")
return render(request, 'location_test.html', {'FirstLoc_list_obj': FirstLoc_list_obj, 'SecondLoc_list_obj': SecondLoc_list_obj})
else:
print("Location Not Found")
return render(request, 'location_test.html', {})
return render(request, 'location_test.html', {})
return render(request, 'location_test.html', {})
urls.py
urlpatterns = [
path('search/', views.search, name="search"),
]
location_test.html
<form type="get" action="#" style="margin: 0">
{% csrf_token %}
<label>Locations:-</label>
<input id="search_box" type="text" name="search_box" placeholder="Search..." >
<button id="search_submit" type="submit" >Submit</button>
</form>
答案 0 :(得分:0)
正如我在评论中所说,您不能将icontains
与None
值一起使用。试试这个:
def search(request):
if request.method == 'GET':
form = LocForm(request.POST)
if form.is_valid():
search_query = request.GET.get('search_box', None)
if search_query:
FirstLoc_list_obj = FirstLoc_List.objects.filter(address__icontains=search_query)
SecondLoc_list_obj= SecondLoc_list.objects.filter(address__icontains=search_query)
答案 1 :(得分:0)
如果没有,则可以使用空字符串,例如:
search_query = request.GET.get('search_box')
if not search_query :
search_query = ""
答案 2 :(得分:0)
这是唯一讨论这个错误的地方。所以这不是问题的完美答案,但我希望它对其他人有用。
我没有表单,只有一个 URL 来检查,但是当用户以我不希望的方式进入页面时,它不应该引发错误。所以我把所有的东西都放在一个 if 语句中。
if request.GET.get("q") != None:
query = request.GET.get("q")
context["array"] = Database.objects.filter(DB__item__contains=query)