Imagine that I have a dictionary in my Django application:
dict = {'a': 'one', 'b': 'two', }
Now I want to easily create an urlencoded list of GET parameters from this dictionary. Of course I could loop through the dictionary, urlencode keys and values and then concatenate the string by myself, but there must be an easier way. I would like to use a QueryDict instance. QueryDict is a subclass of dict, so it should be possible somehow.
qdict = QueryDict(dict) # this does not actually work print qdict.urlencode()
How would I make the second to last line work?
class QueryDict. In an HttpRequest object, the GET and POST attributes are instances of django.http.QueryDict , a dictionary-like class customized to deal with multiple values for the same key. This is necessary because some HTML form elements, notably <select multiple> , pass multiple values for the same key.
MultiValueDict is a dictionary subclass that can handle multiple values assigned to a key.So you should pass values of dict as list . here, 1->[1] . In an HttpRequest object, the GET and POST attributes are instances of 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.
How about?
from django.http import QueryDict ordinary_dict = {'a': 'one', 'b': 'two', } query_dict = QueryDict('', mutable=True) query_dict.update(ordinary_dict)
Python has a built in tool for encoding a dictionary (any mapping object) into a query string
params = {'a': 'one', 'b': 'two', } urllib.urlencode(params) 'a=one&b=two'
http://docs.python.org/2/library/urllib.html#urllib.urlencode
QueryDict
takes a querystring as first param of its contstructor
def __init__(self, query_string, mutable=False, encoding=None):
q = QueryDict('a=1&b=2')
https://github.com/django/django/blob/master/django/http/request.py#L260
Update: in Python3, urlencode has moved to urllib.parse:
from urllib.parse import urlencode params = {'a': 'one', 'b': 'two', } urlencode(params) 'a=one&b=two'
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