I have made a form to filter ListView
class SingleNewsView(ListView):
model = News
form_class = SearchForm
template_name = "single_news.html"
def get(self, request, pk, **kwargs):
self.pk = pk
pub_from = request.GET['pub_date_from']
pub_to = request.GET['pub_date_to']
return super(SingleNewsView,self).get(request,pk, **kwargs)
My form fields are pub_date_from
and pub_date_to
. When I run the site it says:MultiValueDictKeyError
.
I don't know what's going on. When I remove the two line of getting pub_from
and pub_to
the site works fine. I want these two values to filter the queryset.
First check if the request object have the 'is_private' key parameter. Most of the case's this MultiValueDictKeyError occurred for missing key in the dictionary-like request object. Because dictionary is an unordered key, value pair “associative memories” or “associative arrays” In another word.
What is Is_private in Django? The line is is_private = request.POST['is_private'] The problems lies within the form, the is_private is represented by a checkbox. If the check box is NOT selected, obviously nothing is passed. This is where the error gets chucked.20-May-2020.
Django uses request and response objects to pass state through the system. When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function.
On first request there is no form data submitted so request.GET
would not have any data. So doing request.GET['pub_date_from']
will fail. You shall use .get()
method
pub_from = request.GET.get('pub_date_from')
pub_to = request.GET.get('pub_date_to')
If these keys are not in the dict, will return None
. So handle the such cases appropriately in your code.
Also, if you want to filter objects for ListView
add get_queryset()
method to return filtered queryset as explained here Dynamic filtering
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With