Django MultiValueDictKeyError by querying an object

I made a filter form 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 pub_date_fromand pub_date_to. When I run the site, he says
MultiValueDictKeyError.

I do not know what's going on. When I delete two lines of receipt pub_fromand pub_to, the site works fine. I want these two values ​​to filter the request.

Any help plz

+4
source share
1 answer

At the first request, there is no form data, therefore, request.GETit will not have any data. Thus, execution request.GET['pub_date_from']will fail. You must use the method.get()

pub_from = request.GET.get('pub_date_from')
pub_to = request.GET.get('pub_date_to')

dict, None. .

, ListView add get_queryset() ,

+5

Source: https://habr.com/ru/post/1545335/


All Articles