1

I have an output like this.

data = <QueryDict: {u'product_name': [u'L4'], u'price': [u''], u'product_description': [u''], u'id': [u"[u'1']"], u'product_status': [u'1']}>

Honestly I have no idea how the output is like this but if I want to get the id.

I used something like this (data['id'][0]) but this isn't getting my anything and if I use (data['id']) this is what I get u'[u\\'1\\']

When I post this kind of data, I get such an error invalid literal for int() with base 10: '['

dda
  • 6,030
  • 2
  • 25
  • 34
Tsuna
  • 2,098
  • 6
  • 24
  • 46
  • You should probably fix the form or JS that is sending this data; there's no reason for the `id` value to be wrapped in a list. – Daniel Roseman Dec 20 '16 at 09:08
  • Possible duplicate of [How to change a django QueryDict to Python Dict?](http://stackoverflow.com/questions/13349573/how-to-change-a-django-querydict-to-python-dict) – ettanany Dec 20 '16 at 09:09
  • @ettanany I read it, but what I really need is taking the `u` out of it so I can get like the value `1` for to search for query – Tsuna Dec 20 '16 at 09:15
  • @DanielRoseman I get what you mean, I am super new with django and the one who worked on it in actually away at the moment, so trying to do it this way, hopefully it's fast and easy and let the one who developed it now and do the adjustment later – Tsuna Dec 20 '16 at 09:19
  • are you using django-rest-framework on this view ? – Pulkit Pahwa Dec 22 '16 at 10:12

2 Answers2

0

You need to convert it to an ordinary dictionary, like below:

my_dict = dict(data.iterlists())

Now, you should be able to do my_dict['id'][0]

You can use ast.literal_eval() to fix your issue, but as mentioned by @Daniel, you may need to fix the source of your data.

>>> import ast
>>> 
>>> id = ast.literal_eval("[u'1']")
>>>
>>> id
[u'1']
>>> id[0]
u'1'
ettanany
  • 19,038
  • 9
  • 47
  • 63
  • I am actually trying to get the id and then use it to get a query but then would give me this error after using your code though `invalid literal for int() with base 10: "[u'1']"` – Tsuna Dec 20 '16 at 09:10
  • Please a look at the edit. Also, which result are you getting now when you use `my_dict['id']`? – ettanany Dec 20 '16 at 09:28
  • if I run `(my_dict[u'id'][0])` now I get `u'[u\\'2\\']'` – Tsuna Dec 20 '16 at 09:54
  • 1
    You can still do `int(ast.literal_eval(ast.literal_eval("u'[u\\'2\\']'"))[0])` but you should not! You need to fix your error from its source. – ettanany Dec 20 '16 at 12:08
0

Probably you are trying to read the data using request.data. You should try request.POST.

So, in your case, to read the product_name, you can do this: request.POST['product_name'] and likewise for other fields.

Pulkit Pahwa
  • 1,412
  • 11
  • 8