Cyzanfar
Cyzanfar

Reputation: 7136

Django template pass array to input field

I have a hidden input field in my django template where I'm passing as value an array.

  <form method="post" action="{% url 'flights:flight-selection' %}">{% csrf_token %}
    <input type="hidden" id="fa_f_ids" name="fa_f_ids" value="{{ value.fa_f_ids }}">
    <button type="submit" class="btn btn-light">Select</button>
  </form>

When I submit this form via post request I want to get the value of fa_f_ids as an array but I am getting a string instead when I'd like to get an array.

request.POST.get("fa_flight_id")
#=> <QueryDict: {'csrfmiddlewaretoken': ['UoYqbTUlNxTEJW5AUEfgsgsLuG63dUsvX88DkwGLUJfbnwJdvcfsFhi75yie5uMX'], 'fa_f_ids': ["['AMX401-1560750900-schedule-0000', 'AMX19-1560782100-schedule-0001']"]}>

Upvotes: 0

Views: 1377

Answers (1)

ivissani
ivissani

Reputation: 2664

You need to split the array into several hidden fields, each representing one position of your array:

  <form method="post" action="{% url 'flights:flight-selection' %}">
    {% csrf_token %}
    {% for val in value.fa_f_ids %}
        <input type="hidden" name="fa_f_ids[{{ forloop.counter0 }}]" value="{{ val }}">
    {% endfor %}
    <button type="submit" class="btn btn-light">Select</button>
  </form>

Upvotes: 1

Related Questions