django MultiValueDictKeyError在请求获取对象时 [英] django MultiValueDictKeyError while requesting get object
问题描述
我已经制作了一个表单来过滤 ListView
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)
我的表单字段是 pub_date_from
和 pub_date_to
。当我运行该网站时,它说:
MultiValueDictKeyError
。
My form fields are pub_date_from
and pub_date_to
. When I run the site it says:
MultiValueDictKeyError
.
我不知道这是怎么回事。当我删除获得 pub_from
和 pub_to
的两行时,该网站运行正常。我希望这两个值可以过滤查询集。
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.
任何帮助plz
推荐答案
在第一次请求时,没有提交表单数据,因此 request.GET
将没有任何数据。因此,执行 request.GET ['pub_date_from']
将失败。您应使用 .get()
方法
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')
如果这些键不在字典中,将返回 None
。因此,请在您的代码中适当地处理此类情况。
If these keys are not in the dict, will return None
. So handle the such cases appropriately in your code.
此外,如果要过滤 ListView
的对象,请添加 get_queryset()
方法可返回过滤的查询集,如此处动态过滤
Also, if you want to filter objects for ListView
add get_queryset()
method to return filtered queryset as explained here Dynamic filtering
这篇关于django MultiValueDictKeyError在请求获取对象时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!