Search code examples
pythondjango

How to POST over multiple variables using forms in Django


Using HTML forms if you wanted to POST over multiple variables you would have to set the name of your input field to "name[]", and then when you POST['name'] you can get the information form every input field with the name "name[]". Currently I am working with Django, and implementing a view that involves a form that will POST over a variable amount of variables. When I try to implement the same method as described above in Django, I am getting a "MultiValueDictKeyError" instead. By removing the brackets in the input variables name I no longer get the error, but it will only POST over the last value, and I need it to POST over all the values.


/* In template example.html */
<form action = "{% url view_name %}" method = POST>

/* Variable amount of these inputs */
<input type = "input" name = "name[]">
<input type = "input" name = "name[]">

<input type = "submit" name = "submit" value = "Submit">
</form>

#View example located in views.py
class view_name(request):
     #Error occurs at below line
     postVar = request.POST["name"]
     

Solution

  • Try using the following:

    postVar = request.POST.getlist('name[]')
    

    You might need to remove the [] from the input html.