django 在 / 'q' 处返回 MultiValueDictKeyError



django返回MultiValueDictKeyError at/"问">在我的仪表板模板,当我试图添加搜索功能到我的应用程序。我想当一个用户在搜索输入上键入的东西,以返回用户搜索的值。但是当我尝试自己做时,我最终得到了一个错误。

MultiValueDictKeyError at /
'q'
def dashboard(request):
photos = Photo.objects.all()
query = request.GET['q']
card_list = Photo.objects.filter(category__contains=query)
context = {'photos': photos, 'card_list':card_list}
return render(request, 'dashboard.html', context) 

<div class="container">
<div class="row justify-content-center">
<form action="" method="GET">
<input type="text" name="q" class="form-control">
<br>
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>   
<br>
<div class="container">
<div class="row justify-content-center">
{% for photo in photos reversed %}
<div class="col-md-4">  
<div class="card my-2">
<img class="image-thumbail" src="{{photo.image.url}}" alt="Card 
image cap">

<div class="card-body">
<h2 style="color: yellowgreen; font-family: Arial, Helvetica, 
sans-serif;">
{{photo.user.username.upper}}
</h2>
<br>
<h3>{{photo.category}}</h3>
<h4>{{photo.price}}</h4>  
</div>
<a href="{% url 'Photo-view' photo.id %}" class="btn btn-warning btn- 
sm m-1">Buy Now</a>
</div>
</div>
{% empty %}
<h3>No Files...</h3>
{% endfor %} 
</div> 
</div>

try this

query = request.GET['q']
query = request.GET.get('q', '')  # use get to access the q

get()方法返回具有指定键的项的值。

相关内容

  • 没有找到相关文章

最新更新