Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django MultiValueDictKeyError while requesting get object

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.

like image 235
Aaeronn Avatar asked Jun 20 '14 08:06

Aaeronn


People also ask

What is Multivaluedictkey error?

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?

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.

What is request get in Django?

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.


1 Answers

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

like image 134
Rohan Avatar answered Oct 19 '22 09:10

Rohan