开发者

How to see if a Django QueryDict key matches a pattern

I'm working on a site with a list-type view (shopping cart) where each item has a select drop-down widget to change shipping type. The resulting HTML, created by a for loop such that 'item_id_foo' changes on each cycle, looks like:

<select name='item_id_foo'>
<option value='bar1'>bar1</option>
...
<input type='submit' name='submit' value='Change'/>
</select>

As a result, by request.POST.copy has a key/value like {'item_id_foo':'bar1'}. My question is how to find keys that look like 'item_id_foo', 'item_id_bar', etc. Methods like "getitem", "get" or "contains" assume you know what the full key looks like, and I only know the pattern开发者_开发问答. How do I match for a pattern on a key?

Thank you, bkev

Update: Example values for the select would be like: 'item_id_1', 'item_id_2', 'item_id_3'...matching the id of the item in the cart that needs to be edited (each has its own shipping method and fee).


Why not loop through the entire list and then do regex on each item's name? QueryDict.lists() or QueryDict.values() allows you to get all of it and then loop through that.

QueryDict.lists() Like items(), except it includes all values, as a list, for each member of the dictionary.

For example:

>>> q = QueryDict('a=1&a=2&a=3')
>>> q.lists()
[(u'a', [u'1', u'2', u'3'])]

Link: http://docs.djangoproject.com/en/dev/ref/request-response/#django.http.QueryDict


Just iterate over the keys and keep those you want

>>> post = {'item_id_1': 1, 'item_id_2': 2, 'item_id_3': 3, 'noitem': 0}
>>> dict([(k, v) for k, v in post.items() if k[:8] == 'item_id_'])
{'item_id_3': 3, 'item_id_2': 2, 'item_id_1': 1}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜