For example, if you submit the POST
request values' list in index.html
as shown below:
{# "index.html" #}
<form action="{% url 'my_app1:test' %}" method="post">
{% csrf_token %}
<input type="text" name="fruits" value="apple" /></br>
<input type="text" name="fruits" value="orange" /></br>
<input type="submit" />
</form>
Then, you can get the POST
request values' list in my_app1/views.py
as shown below. *According to my experiments, you cannot properly get the POST
request values' list in Django Templates and my answer explains how to get a GET
request values' list in Django and my answer explains how to get POST
request values in Django:
# "my_app1/views.py"
from django.shortcuts import render
def test(request):
print(request.POST.getlist('fruits')) # ['apple', 'orange']
print(request.POST.getlist('meat')) # []
print(request.POST.getlist('meat', "Doesn't exist")) # Doesn't exist
print(request.POST._getlist('fruits')) # ['apple', 'orange']
print(request.POST._getlist('meat')) # []
print(request.POST._getlist('meat', "Doesn't exist")) # Doesn't exist
print(list(request.POST.lists())) # [('csrfmiddlewaretoken', ['OE3hidxt0awKjRFXxUddvT6u0cRfhdMnsVGpsYWAhd0hMUabpY3vFp6xkCub9Jlb']), ('fruits', ['apple', 'orange'])]
print(dict(request.POST)) # {'csrfmiddlewaretoken': ['OE3hidxt0awKjRFXxUddvT6u0cRfhdMnsVGpsYWAhd0hMUabpY3vFp6xkCub9Jlb'], 'fruits': ['apple', 'orange']}
return render(request, 'index.html')
In addition, if you submit the POST
request values' list in index.html
as shown below:
<form action="{% url 'my_app1:test' %}" method="post">
{% csrf_token %}
<input type="text" name="fruits" value="apple,orange" />
<input type="submit" />
</form>
Then, you can get the POST
request values' list in my_app1/views.py
as shown below:
# "my_app1/views.py"
from django.shortcuts import render
def test(request):
print(request.POST['fruits'].split(',')) # ['apple', 'orange']
print(request.POST.getlist('fruits')[0].split(',')) # ['apple', 'orange']
print(request.POST._getlist('fruits')[0].split(',')) # ['apple', 'orange']
print(list(request.POST.values())[1].split(',')) # ['apple', 'orange']
print(list(request.POST.items())[1][1].split(',')) # ['apple', 'orange']
print(list(request.POST.lists())[1][1][0].split(',')) # ['apple', 'orange']
print(request.POST.dict()['fruits'].split(',')) # ['apple', 'orange']
print(dict(request.POST)['fruits'][0].split(',')) # ['apple', 'orange']
return render(request, 'index.html')
Then, you can get the POST
request values' list in test.html
as shown below:
{# "test.html" #}
{{ request.POST.fruits }} {# apple,orange #}
{{ request.POST.dict }} {# {'csrfmiddlewaretoken': 'y2yGzMMJq2kVXGLUZ68JJxpNbYpFxZyRcjbOJxbQH5OsqJg8RaY1T3pQvo2Bpv7F', 'fruits': 'apple,orange'} #}