Reputation: 3856
In my Django application, I have a POST request QueryDict whose values I am trying to change. I understand that QueryDict objects are immutable, so I instantiated a QueryDict item that is mutable. The crux of the problem is that the value is a byte string of comma separated numbers coming in from a AJAX call in the front end of the application, e.g. U"2,4,6,7".
Each key value in a QueryDict is inherently a list of values, [U'2', U'4'] so I need to change the single byte U"2,4,6,7" posted from my front end into a list of byte strings [U'2', U'4', U'6', '7']. The problem however is whenever I try to do a split on the string and assign the request POST key value to that new split string, the key value is a list, in a list. e.g. {'expertise': [[U'2', U'4']]}. I tried a contrived solution by iterating through a split list of the values, and appending them into the key value of the request POST item, but it gives me the error
AttributeError: 'unicode' object has no attribute 'append'
In a mutable QueryDict object, if each QueryDict item is a list, and it has no value append, than how is it possible to edit the list item ? Is there a simpler way of accomplishing this ?
View Function Code
mentors = Mentor.objects.filter(is_active=True, is_verified=True).order_by('last_name', 'first_name')
ajax_post = dict(request.POST.iteritems())
post = QueryDict('', mutable=True)
post.update(ajax_post)
for key in post:
postlist = post[key].split(',')
for item in postlist:
post[key].append(item)
# First attempt that gives list in a list
# for item in post:
# post[key] = post[key].split(',')
form = MentorSearchForm(data=post)
if form.is_valid():
mentors = filter_mentors(form.cleaned_data)
Upvotes: 0
Views: 1354
Reputation: 309089
You're getting caught out by the QueryDict.__setitem__
. When you do querydict['key'] = value
, it sets the key to [value]
, not value
.
You can use the QueryDict.setlist
method to set the given key to the given list.
querydict = QueryDict('', mutable=True)
for key in request.POST.iteritems():
postlist = post[key].split(',')
querydict.setlist(key, postlist)
Since you are going to loop through every key in the post data, I think you can remove the update()
step from your code.
Upvotes: 3
Reputation: 6572
If I've understood the constraints correctly, you should use builtin array type.
>>> q = U"2,4,6,7"
>>> import array
>>> ary = array.array('u', q)
>>> [i for i in ary if i.isdigit()]
[u'2', u'4', u'6', u'7']
Upvotes: 1