django one submit form several input same name

Question:

In a template i have one form with several inputs same name as in the example below.
(the name of the inputs is allways the same, but the value is different, for example rate in one case is 743.80 and in the other form 669.32).
I need to know how to post all the same name inputs without they repalce each other. In PHP I was using name="rate[]" and then for each, but i donĀ“t have idea, how to make with it python/django.
Any idea?

<form method="POST">

    <input type="hidden" name="hotel" value="{{ hotel.id }}" >
    <input type="hidden" name="room" value="{{ room.id }}" >
    <input type="hidden" name="policy" value="1" >
    <input type="hidden" name="rate" value="743.80" >
    <select name="qty">
    <option value="0">0</option>
    <option value="1">1</option>
    <option value="2">2</option>
    </select>

    <input type="hidden" name="hotel" value="{{ hotel.id }}" >
    <input type="hidden" name="room" value="{{ room.id }}" >
    <input type="hidden" name="policy" value="1" >
    <input type="hidden" name="rate" value="669.32" >
    <select name="qty">
    <option value="0">0</option>
    <option value="1">1</option>
    <option value="2">2</option>
    </select>

  <input type="submit" value="Enviar">
  </form>
Asked By: Angel Valdez

||

Answers:

you can use get_list for example:

rates = request.POST.getlist('rate')

details here QueryDict.getlist search the description for QueryDict.getlist, and here django-getlist humanly

Answered By: Brown Bear

You’re better off using AJAX, serializing your form and posting an array of objects that group the inputs together by section and not by input name. The method you’re using now is prone to errors when mapping the form values on the backend since what you’re trying to do would group values by name and not by their input groups.

Answered By: marchWest

You should use formsets for this.

Answered By: Daniel Roseman
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.