I have a code that is behaving really strange. The view receives a POST request with a key "tags[]"
, it is a list. I need to get that list but request.POST.get()
only returns the last item of the list. This is the code:
....
elif request.method == "POST":
print("REQUEST POST:")
print(request.POST)
print("---------------------------")
tags = request.POST.get("tags[]")
print("tags: %s" % tags)
print("---------------------------")
And it prints the following:
REQUEST POST:
<QueryDict: {'csrfmiddlewaretoken': ['PAgg9VKGosBQUn8tBBb09NdeVgE8tcAaQz2EMbkQZPiJi289hBf7MHIKM1jF8mvp'], 'event_type_description': ['live_course'], 'title': [''], 'description': [''], 'platform_name': ['Zoom'], 'other_platform': [''], 'record_date': [''], 'date_start': [''], 'date_end': [''], 'time_day': ['12:00 PM'], 'schedule_description': [''], 'tags[]': ['not', 'normal', 'very', 'strange'], 'event_picture': ['']}>
---------------------------
tags: strange
---------------------------
As you can see, the value of the tags
variable is "strange", the last item in the list. Why not all the list? request.POST.get
is behaving in an unexpected way. Am I missing something?
Yes. This is not the same as with a regular python dict. If you need a list of all values, you must use QueryDict.getlist instead of .get
tags = request.POST.getlist("tags[]")
https://docs.djangoproject.com/en/3.1/ref/request-response/#django.http.QueryDict.getlist