user18982103
user18982103

Reputation:

django returns MultiValueDictKeyError at / 'q'

django returns MultiValueDictKeyError at / 'q' in my dashboard template when I'm trying to add search functionality into my app. I want when a user type something on the search input to return the value that user searched for. but i endup getting an error when i try to do it myself.

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>

Upvotes: 0

Views: 59

Answers (1)

rahul.m
rahul.m

Reputation: 5854

try this

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.

Upvotes: 0

Related Questions