1

i´m new here and in python. I think my problem is very simple, but I can´t solve it. I have a form with a checkbox. I send 4 selected options, and the querydict recognizes them. But when I ask it to print the 4 values, it only brings me the last one.

This is my html:

enter image description here

I send the form and it goes to def dietPlan in views.py:

def dietPlan(request):
    # Obtengo los datos que vienen del formulario
    querydict=request.POST
    print((querydict))
    print((querydict['opcionesCena']))
    print(len(querydict['opcionesCena']))

But, the prints are:

<QueryDict: {'csrfmiddlewaretoken': ['qNAKsaNlPOO3UY7X76sNy1bEuidxd4WDvUlwJXD6BYxA1JTkyra0A86eYMHJfJ3B'], 'opcionesCena': ['AlimentoID352', 'AlimentoID356', 'AlimentoID360', 'AlimentoID364']}>
AlimentoID364
13

Only recognize AlimentoID364 (the last one of the 4) and it takes the number of characters in AlimentoID364.

I need to count how many values are for the key 'opcionesCena': if there are 4, or 5, or whatever.

Could you help me? Thanks in advance

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Maybe try converting it from a QueryDict to a dictionary. See https://stackoverflow.com/questions/13349573/how-to-change-a-django-querydict-to-python-dict – Barmar Jan 04 '23 at 18:00
  • To clarify, Do you need to know how many values are associated with each key? Or, Do you need the actual values from each key? – Trevor Winge Jan 04 '23 at 18:00

2 Answers2

0

As the object is a QueryDict you should use:

querydict.getlist('opcionesCena')

to print the list object from the dict.

Source

Andrew Ryan
  • 1,489
  • 3
  • 15
  • 21
0

If you just need to know how many values are associated with each key then you could use something like this.

for key, value in querydict.items():
    #print value
    print(key, len([item for item in value if item]))