0

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']"]}>
3
  • I had the same problem when I was getting the data from the request. I've searched a lot about this and the only solution that worked out for me was converting the querydict into a python dict and extracting the array from the value. Commented Jun 18, 2019 at 20:08
  • you can use request.POST.getlist, to change string into array Commented Jun 18, 2019 at 20:33
  • I tried that, doesn't work. .getlist returns this: ["['AMX401-1560750900-schedule-0000', 'AMX19-1560782100-schedule-0001']"] Commented Jun 18, 2019 at 20:34

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

How do I retrieve the values in the view? fa_f_ids[0]': ['AMX401-1560750900-schedule-0000'], 'fa_f_ids[1]': ['AMX19-1560782100-schedule-0001']}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.