4

I have a form with multiple select field. It is working through GET method. An example of request parameters generated by the form:

action=not-strummed&action=not-rewarded&keywords=test&page=2

Note that there is two "action" parameters. This is happening because of the multiple select.
What I want to do is:

  • Make a dict from parameters
  • Remove "page" key from the dict
  • Transform-back the dict into the parameter string

The urllib.urlencode() isn't smart enough to generate url parameters from the list.

For example:

{
     "action": [u"not-strummed", u"not-rewarded"]
}

urllib.urlencode() transforms this dict as:

action=%5Bu%27not-strummed%27%2C+u%27not-rewarded%27%5D

This is completely wrong and useless.

That's why i wrote this iteration code to re-generate url parameters.

parameters_dict = dict(self.request.GET.iterlists())
parameters_dict.pop("page", None)
pagination_parameters = ""
for key, value_list in parameters_dict.iteritems():
    for value in value_list:
        pagination_item = "&%(key)s=%(value)s" % ({
            "key": key,
            "value": value,
        })
        pagination_parameters += pagination_item

It is working well. But it doesn't cover all possibilities and it is definitely not very pythonic.

Do you have a better (more pythonic) idea for creating url parameters from a list?

Thank you

2
  • request.GET return dict with parameters. request.GET['action'], for example. Commented Jul 21, 2013 at 15:38
  • You can read it with .lists() Commented Jul 21, 2013 at 16:00

1 Answer 1

15

You should be able to use the second doseq parameter urlencode offers:

http://docs.python.org/2/library/urllib.html

So basically, you can pass a dictionary of lists to urlencode like so:

urllib.urlencode(params, True)

And it will do the right thing.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.