I think this method is handy, since you don't need to remember if you need urlquote or urlencode. It does both and adds a question mark between the path and the get parameters, if later are present.
And it works around a bug in Django: MultiValueDicts (request.GET, request.POST) are handled correctly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | from django.utils.http import urlquote as django_urlquote
from django.utils.http import urlencode as django_urlencode
from django.utils.datastructures import MultiValueDict
def urlquote(link=None, get={}):
u'''
This method does both: urlquote() and urlencode()
urlqoute(): Quote special characters in 'link'
urlencode(): Map dictionary to query string key=value&...
HTML escaping is not done.
Example:
urlquote('/wiki/Python_(programming_language)') --> '/wiki/Python_%28programming_language%29'
urlquote('/mypath/', {'key': 'value'}) --> '/mypath/?key=value'
urlquote('/mypath/', {'key': ['value1', 'value2']}) --> '/mypath/?key=value1&key=value2'
urlquote({'key': ['value1', 'value2']}) --> 'key=value1&key=value2'
'''
assert link or get
if isinstance(link, dict):
# urlqoute({'key': 'value', 'key2': 'value2'}) --> key=value&key2=value2
assert not get, get
get=link
link=''
assert isinstance(get, dict), 'wrong type "%s", dict required' % type(get)
assert not (link.startswith('http://') or link.startswith('https://')), \
'This method should only quote the url path. It should not start with http(s):// (%s)' % (
link)
if get:
# http://code.djangoproject.com/ticket/9089
if isinstance(get, MultiValueDict):
get=get.lists()
if link:
link='%s?' % django_urlquote(link)
return u'%s%s' % (link, django_urlencode(get, doseq=True))
else:
return django_urlquote(link)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.