Home > Enterprise >  Django QueryDict How to ensure that the "plus" does not disappear in the QueryDict?
Django QueryDict How to ensure that the "plus" does not disappear in the QueryDict?

Time:10-19

How to ensure that the "plus" does not disappear in the QueryDict?

I am trying to parse the received get-query into a dict:

from urllib.parse import quote_plus

my_non_safe_string = "test=1 1" # This example, the string can be anything. (in GET query format)
QueryDict(my_non_safe_string)
out: <QueryDict: {'test': ['1 1']}>

my_safe_string = quote_plus("test=1 1") # 'test=1+1'
out: <QueryDict: {'test=1 1': ['']}>

I would like to get the following result:

<QueryDict: {'test=1 1': ['1 1']}>

CodePudding user response:

How about this?

In [1]: from django.http import QueryDict

In [2]: from urllib.parse import quote_plus

In [3]: key = quote_plus("test=1 1")

In [4]: value = quote_plus("1 1")

In [5]: query_str = f"{key}={value}"

In [6]: QueryDict(query_str)
Out[6]: <QueryDict: {'test=1 1': ['1 1']}>

CodePudding user response:

You need to percentage encode the plus, by use quote_plus you also encode the equal sign (=) and therefore the QueryDict can not parse it effectively:

my_safe_string = f'test={quote_plus("1 1")}'

this produces:

>>> from urllib.parse import quote_plus
>>> my_safe_string = f'test={quote_plus("1 1")}'
>>> QueryDict(my_safe_string)
<QueryDict: {'test': ['1 1']}>

If it is unclear if the key contains any characters that should be escaped, you can use:

key = 'test'
value = '1 1'
my_safe_string = f'{ quote_plus(key) }={ quote_plus(value) }'
  • Related