Why can't I get the key/value pairs of this simple Python dictionary?
QueryDict
is a class, similar to the dict
class.
.keys()
is an instance method, but you're calling it on the class, so you need to pass the instance to the method
>>> mydict = {'key': 'value'}
>>> mydict.keys() # instance method, works
['key']
>>> dict.keys() # no argument, on class, same error you get
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: descriptor 'keys' of 'dict' object needs an argument
>>> dict.keys(mydict) # passing in mydict
['key']
Edit:
After some research, it looks like request.GET
and request.POST
are both instances of the request.QueryDict
class. So instead of request.QueryDict.keys()
, what you want to call is:
request.GET.keys()
Saqib Ali
Updated on June 27, 2022Comments
-
Saqib Ali almost 2 years
I'm building a restful API for a Django application using the Django-Rest-Framework.
Within the viewset function, I'm examining the value of the response and trying to find out what methods I can call on it. I'm doing this by printing simple log messages. However, when I try to call one of those methods (keys) on the QueryDict (which after all is just a dictionary), I get the error: TypeError: descriptor 'keys' of 'dict' object needs an argument. Why? How do I fix it?
>>> logger.info("request.QueryDict = %s" % request.QueryDict) [2014-02-25 17:21:30] INFO [myApp.views:2352] request.QueryDict = <class 'django.http.request.QueryDict'> # Works! >>> logger.info("dir(request.QueryDict) = %s" % dir(request.QueryDict)) [2014-02-25 17:21:30] INFO [myApp.views:2354] dir(request.QueryDict) = ['__class__', '__cmp__', '__contains__', '__copy__', '__deepcopy__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_assert_mutable', '_encoding', '_iteritems', '_iterlists', '_itervalues', '_mutable', 'appendlist', 'clear', 'copy', 'dict', 'encoding', 'fromkeys', 'get', 'getlist', 'has_key', 'items', 'iteritems', 'iterkeys', 'iterlists', 'itervalues', 'keys', 'lists', 'pop', 'popitem', 'setdefault', 'setlist', 'setlistdefault', 'update', 'urlencode', 'values', 'viewitems', 'viewkeys', 'viewvalues'] # Works! >>> logger.info("request.QueryDict.keys() = %s" % request.QueryDict.keys()) TypeError: descriptor 'keys' of 'dict' object needs an argument # Fails!