3

Can someone point me in the right direction. Essentially, I have a <form> that has a variable number of fields:

<input value="1" name="cat">
<input value="2" name="dog">
<input value="3" name="tiger">

When I look at the request.POST, the dictionary order is off:

{'dog':['2'], 'cat':[1], 'tiger':['3']}

I realize that dictionary ordering is not maintained within Python - however I need a way to get that ordering back on the backend.

How could I go about doing this? My first idea is using JS, but I was hoping there would be a better way.

davidsbro
  • 2,761
  • 4
  • 23
  • 33
Mmm Donuts
  • 9,551
  • 6
  • 27
  • 49
  • use collections.OrderedDict([items]) find out more [here](https://docs.python.org/2/library/collections.html#collections.OrderedDict) – Nobi Jul 04 '14 at 14:07
  • it depends of what you need after but you can convert you dict in list of tuples like that : http://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value – Freelancer Jul 04 '14 at 14:08
  • I think the POST request comes in unordered though. Django converts the HTTP request to a dictionary. I would need to hijack that process to use the above method - right? – Mmm Donuts Jul 04 '14 at 14:12
  • I'm trying to think of a reason why you would need to rely on the order of fields. Why not use some explicit naming convention instead? – Daniel Roseman Jul 04 '14 at 14:21
  • So the fields are 'sortable' - the mod removed that little tidbit. I need to hold the order because I want to be able to create and save custom forms via sorting them on the frontend. – Mmm Donuts Jul 04 '14 at 14:33
  • @SomeDeveloper you should submit the sort order as separate field(s) – Anentropic Jul 04 '14 at 15:07

1 Answers1

4

For those who are asking why you'd need to rely on the order of the fields - there are cases. In my case, I was accepting a PayPal IPN, which required the data to be hashed in a correct order for the response.

Anyway, this was my original question: Retrieve POST data in the order they were sent in in Django

You can basically use HttpRequest.body (this was called raw_post_data in 1.4 and below). However - remember that it is up to the browser to send the data, and I don't know whether browsers guarantee order of the form fields when you submit the form.

Community
  • 1
  • 1
Ben
  • 6,687
  • 2
  • 33
  • 46