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

Тел: +7 965 3737 888

578

Просмотров

3

Ответов

Manipulate URL query strings using context variables using a template tag

A template tag that includes a modified version of the GET query string. the query string can be manipulated by adding and removing fields. If a value is given that resolves to a context variable that the value of the variable is used. Based on this snippet by dnordberg, but with the ability to use context and done in a cleaner manner, without the need to add an arbitrary template.

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

Ответы (3):

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

How can I pass a python variable within a double quoted argument of the template tag?

Im trying to create the paginator links, next, previous, etc.. In the query string I might have different parameters apart from "page" and thus to iterate from pages I want to modify only this parameter in the query string.. Something like this:

<a href="{% query_string "page={{ next }}" "page" %}"> Next </a>

which obviously doesnt work since django interprets what is inside double quotes as literal string, so it doesnt resolve the variable's value.

How can I do this? Do I need to change the templatetag and send an extra argument (the page variable) ?

Cheers

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

django.http.QueryDict is your friend

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

Very useful snippet, but as it stands it's 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' at the top, and changing line 73 to:

return mark_safe('?' + '&amp;'.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...)