Задать вопрос

Тел: +7 965 3737 888

555

Просмотров

4

Ответов

Modify query string on a url

Modify a query string on a url. The comments in the code should explain sufficiently. String_to_dict, and string_to_list are also useful for templatetags that require variable arguments.

Вопрос полезен? Да0/Нет0
file_3249.py(2.6Кб)
None

Ответы (4):

Ответmattwestcott:27.11.2010
Ответ полезен? Да0/Нет0

Have just posted this on JHsaunders' snippet, but it seems to apply here too: as it stands, this is vulnerable to a cross-site scripting attack because the URL variables previously provided by the user are passed through mark_safe with no escaping, apart from replacing space characters. This can be fixed by adding 'import urllib' to lib/utils.py, and changing the last line of get_query_string to:

return mark_safe('?' + '&'.join([u'%s=%s' % (urllib.quote_plus(str(k)), urllib.quote_plus(str(v))) for k, v in p.items()]))

(Also, to be completely correct even when autoescaping is turned off, I suspect it should be using a plain '&' to delimit the arguments and passing it back as an unsafe string for the template layer to escape - but I'll leave that for someone else to confirm...)

Ответmlhamel:27.08.2010
Ответ полезен? Да0/Нет0

A great piece of code but it doesn't work with MultipleChoiceField !

The QueryDict object cannot deal with a list values, you have the use the lists function.

A possible implementation might be (for the get_query_string method):

...

def get_query_string(p, new_params=None, remove=None):

"""
Add and remove query parameters. From `django.contrib.admin`.
"""
if new_params is None: new_params = {}
if remove is None: remove = []
for r in remove:
    for k in p.keys():
        if k.startswith(r):
            del p[k]
for k, v in new_params.items():
    if k in p and v is None:
        del p[k]
    elif v is not None:
        p[k] = v
url = ''
for k, v in p.lists():
    for element in v:
        if len(url) == 0:
            url += '?'
        else:
            url += '&amp';
        url+= ''.join('%s=%s' % (k, element)).replace(' ', '%20')
return mark_safe(url)

Ответworksology:30.11.2009
Ответ полезен? Да0/Нет0

This is terrific. I don't use GET parameters all that often, but for filtering/sorting content, this snippet really proved helpful. Thanks so much.

Ответdavenaff:17.09.2008
Ответ полезен? Да0/Нет0

Great, thanks - this totally met my need.

A few notes for others implementing this:

You need to add "django.core.context_processors.request", to your TEMPLATE_CONTEXT_PROCESSORS setting.

You need to add this import to your lib/utils.py (or equivalent):

from django.utils.safestring import mark_safe

And it is also worth mentioning that you need to create _response.html