Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Can I create a QueryDict from a dictionary?

Tags:

python

django

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?

like image 273
winsmith Avatar asked Nov 13 '12 15:11

winsmith


People also ask

What is QueryDict Django?

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.

What is a MultiValueDict?

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.

What is request object 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.


2 Answers

How about?

from django.http import QueryDict  ordinary_dict = {'a': 'one', 'b': 'two', } query_dict = QueryDict('', mutable=True) query_dict.update(ordinary_dict) 
like image 152
miki725 Avatar answered Sep 20 '22 14:09

miki725


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' 
like image 32
dm03514 Avatar answered Sep 22 '22 14:09

dm03514