如何处理通过django表单传递的空输入?



我正在做我的第一个django项目,我遇到了一个问题,我找不到任何可行的解决方案。所以,我正在尝试创建一个电子商务网站。我创建了一个基本的搜索栏,我正试图渲染与输入匹配的一切。问题发生在其中一个边缘情况。如果我发送一个空输入,将引发以下错误:

Exception Value:    
The view mainpages.views.search didn't return an HttpResponse object. It returned None instead.

我试着处理这个,但是我失败了。我一直在寻找答案,但没有成功。我真诚地感谢你的时间!

代码:views.py

def search(request):
if request.method == 'GET' and 'q' in request.GET:
query = request.GET.get('q')
try:
if query:
objects_list= ComputerScienceProducts.objects.filter(
Q(name__icontains=query)
)
if list(objects_list) is None:
return render(request, 'search_error.html')
else:
return render(request, 'search_result.html', {"objects_list": objects_list})
except:
return render(request, 'search_error.html')
else:
return render(request, 'search_error.html')

模板:

{% block cont2 %}
<div class="background"></div>
<div class="inp">
<form action="{% url 'search_results' %}" method="get">
{% csrf_token %}
<label>
<i class="bi bi-search" style="position: absolute; margin-left: 15px;margin-top: 13px;"></i>
<input type="text" placeholder="What are you looking for?" class="search" name="q">
</label>
</form>
</div>
<div class="container" style="margin-top: 20px;">
{% endblock %}
{% block content %}
{% if objects_list %}
{% for prod in objects_list %}
<div class="card" id="cardDisplay">
<img class="card-img-top" src="{{ prod.img.url }}" alt="Card image" id="image_prod">
<div class="card-body">
<h4 class="card-title">  {{ prod.name }}</h4>
<p class="card-text">Price: {{ prod.price }} lei <br>
<a href="{% url 'prod_details'  prod.pk %}" class="card-text">Details</a></p>
<button type="submit" class="btn btn-primary">Add to chart</button>
</div>
</div>
{% endfor%}
{% else %}
<p class="updt"> No item has been matched to your search</p>
{% endif %}
</div>
{% endblock %}

返回所有项…

def search(request):
if request.method == 'GET' and 'q' in request.GET:
query = request.GET.get('q')
if query is None:
query = ""
.....

返回错误页…

def search(request):
if request.method == 'GET' and 'q' in request.GET:
query = request.GET.get('q')
try:
if query:
objects_list= ComputerScienceProducts.objects.filter(
Q(name__icontains=query)
)
if list(objects_list) is None:
return render(request, 'search_error.html')
else:
return render(request, 'search_result.html', {"objects_list": objects_list})
➡➡else:
➡➡return render(request, 'search_error.html')
except:
return render(request, 'search_error.html')
else:
return render(request, 'search_error.html')

相关内容

  • 没有找到相关文章

最新更新