mercredi 22 juillet 2015

Django request.data dictionary returns last item instead of list for post data from a form with checkboxes

I have a form that contains checkboxes like so:

<form action="#" method="post">
    <input type="checkbox" name="languages" value="">All<br>
    <input type="checkbox" name="languages" value="en">En<br>
    <input type="checkbox" name="languages" value="de">De<br>
    <input type="checkbox" name="languages" value="ru">Ru<br>
    <input type="submit" value="Preview">
</form>

when send it, I can check and see all the data under request.data which looks like this:

MergeDict(<QueryDict: {u'languages': [u'', u'en', u'de']}>, <MultiValueDict: {}>)

I managed to get the selected language list using:

dict(request.data.dicts[0].iterlists())['u'languages']

But this seems ridiculous.

Trying a different way I get strange behavior. For example when i try to access request.data['languages'] I get the last item from the list u'de'.

Can anyone explain this weird behavior? Why do I get this strange combination of MergeDict, QueryDict and MultiValueDict? And how should I best extract my list of checked values from it?




Aucun commentaire:

Enregistrer un commentaire