I have a form with only one field, which is MultipleChoiceField . In the template, it prints with two other ModelForm forms inside the same HTML form (as described here ).
When reading all the POST data in the view, everything exists and works correctly, except for the values from this MultipleChoiceField , which displays only the last selected value from the form, if you select it directly from request.POST['field'] - but interestingly enough, if I I print request.POST , everything is selected. How is this possible? It really puzzles my mind.
This is the form:
class EstadosAtendidosForm(forms.Form): estadosSelecionados = forms.MultipleChoiceField(choices = choices.UF.list)
This view:
@login_required @csrf_protect def cadastro_transportadora(request): if request.method == 'POST': print request.POST print len(request.POST['estadosSelecionados']) print request.POST estadosSelecionados = request.POST['estadosSelecionados'] for estado in estadosSelecionados: print estado form_end = EnderecoForm(request.POST) form_transp = TransportadoraForm(request.POST) else: transportadora_form = TransportadoraForm() endereco_form = EnderecoForm() estados_form = EstadosAtendidosForm() return render(request, 'transporte/transportadora/cadastro.html', {'transportadora_form': transportadora_form, 'endereco_form': endereco_form, 'estados_form': estados_form})
And this is the pattern:
{% extends "transporte/base.html" %} {% block main %} <h1>Cadastro de Transportadora</h1> <form enctype="multipart/form-data" action="" method="POST"> {% csrf_token %} <h4>Dados da transportadora</h4> {{ transportadora_form.as_p }} <h4>Endereço</h4> {{ endereco_form.as_p }} <h4>Estados atendidos</h4> {{ estados_form.as_p }} <input type="submit" /> </form> {% endblock %}
The print result in the view, as line 5 through 10, looks like this:
<QueryDict: {u'nome': [u'Test name'], u'bairro': [u'Estrela'], u'logradouro': [u'R. SHudhsu'], u'numero': [u'234'], u'estadosSelecionados': [u'AM', u'RJ', u'SP'], u'telefone': [u'+559965321232'], u'cep': [u'88088888'], u'csrfmiddlewaretoken': [u'mQhxZlbosISw4acZOmTWw6FpaQPwg2lJ'], u'estado': [u'AM'], u'email': [u' test@email.com ']}> 2 <QueryDict: {u'nome': [u'Test name'], u'bairro': [u'Estrela'], u'logradouro': [u'R. SHudhsu'], u'numero': [u'234'], u'estadosSelecionados': [u'AM', u'RJ', u'SP'], u'telefone': [u'+559965321232'], u'cep': [u'88088888'], u'csrfmiddlewaretoken': [u'mQhxZlbosISw4acZOmTWw6FpaQPwg2lJ'], u'estado': [u'AM'], u'email': [u' test@email.com ']}> S P
See that the estadosSelecionados variable really contains 3 values that I selected from the form, right as a list, when I print the whole request.POST data, but when I print only request.POST['estadosSelecionados'] , it doesn’t.
Why? I really need help to figure this out. Thanks.