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 >
<div >
<form action="" method="GET">
<input type="text" name="q" >
<br>
<button type="submit">Search</button>
</form>
</div>
</div>
<br>
<div >
<div >
{% for photo in photos reversed %}
<div >
<div >
<img src="{{photo.image.url}}" alt="Card
image cap">
<div >
<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 %}" >Buy Now</a>
</div>
</div>
{% empty %}
<h3>No Files...</h3>
{% endfor %}
</div>
</div>
CodePudding user response:
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.