django returns MultiValueDictKeyError 在 / 'q'

django returns MultiValueDictKeyError at / 'q'

django returns Mu​​ltiValueDictKeyError 在 / 'q' 在我尝试将搜索功能添加到我的应用程序时在我的仪表板模板中。我希望当用户在搜索输入中键入内容时 return 用户搜索的值。但是当我尝试自己做时,我最终得到了一个错误。

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>

试试这个

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

The get() method returns the value of the item with the specified key.