Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dump request.POST to dict, maintaining multiple value fields?

I want to store ModelForm data in database, in JSONField, to be able to create object from this data later, simply calling:

form = ModelForm(data_from_jsonfield_as_querydict)
if form.is_valid():
    object = form.save()

Problem 1:

I have data in POST:

>>> print request.POST
{u'field-1': u'value1', u'field-2': [u'value-2a', u'value-2b']}

And I have to convert this QueryDict to dict. But if I call request.POST.dict() I lose list values form field-2:

>>> print request.POST.dict()
{'field-1': 'value1', 'field-2': 'value-2b'}

I tried to use request.POST.getlist but then I obtain all values as a lists:

>>> for k in request.POST.keys():
...     print request.POST.getlist(k)
[u'value1']
[u'value-2a', u'value-2b']

I cannot even check if given value in above loop is list instance, because request.POST.get(k) does not return error if the value is list and on the other hand request.POST[k] returns MultiValueDictKeyError for every field.

The only solution which comes to my mind is to loop over all fields obtained by getlist() and convert one-value lists to strings, but it seems to me like overkill.

Problem 2:

Assuming the Problem 1 is resolved and I have dict with form data stored in database, like so:

# object.data
{u'field-1': u'value1', u'field-2': [u'value-2a', u'value-2b']}

When I want to create object using above dict as form data, I have to convert it do QueryDict, which can be simply done by:

querydict = QueryDict('', mutable=True)
querydict.update(object.data)

And then:

form = ModelForm(querydict)

The problem is that when creating querydict from dict with some values which are list instance, all querydict values are wrapped in lists:

print querydict
{u'field-1': [u'value1'], u'field-2': [[u'value-2a', u'value-2b']]}

For that reason, form validation fails for field-2 because getlist for that field returns list of lists (with one value) and not list of values.

like image 781
EMiDU Avatar asked Mar 03 '16 08:03

EMiDU


1 Answers

You could use lists(). The format is compatible with the dict contructor.

post_data = dict(request.POST.lists())
like image 193
Gert Avatar answered Oct 02 '22 20:10

Gert