I have this in my front-end (using AlpineJS to go through a loop) :
x-model="rule.protocol"
:name="'protocol[' + rule.pk + ']'"
:value="rule.protocol"
So the print(request.POST) is like this :
<QueryDict: {'csrfmiddlewaretoken': ['xxx'], 'rules[]': ['18580', '18581', '18582', '18583'],
'type[18580]': ['SSH'], 'protocol[18580]': ['TCP'], 'port_range[18580]': ['343434'],
'ip_range[18580]': ['Custom'], 'source_destination[18580]': ['172.16.16.0/24'],
...
I want request.POST['type[18580]']
as request.POST['type'][18580]
and not as a string (‘type[18580]’)
The post data you are retrieving is form data?
Yes - its form data and I am not using formset.
okay so if your using form you can do something like this
# forms
CHOICES = (
(1, "TEST 1"),
(2, "TEST 2"),
(3, "TEST 3"),
(4, "TEST 4"),
)
class TestForm(forms.Form):
array = forms.MultipleChoiceField(choices=CHOICES)
# view
def test(request, id):
data = {}
if id == "add":
data['obj'] = None
data['form'] = TestForm()
if request.method == "POST":
# request.POST.getlist("array") by using this you can get list of data
print(request.POST.getlist("array"))
data['form'] = TestForm(request.POST)
if request.method == "POST":
if data['form'].is_valid():
return redirect('.')
return render(request, html_path, data)
Let me simplify this :
I have a <form>
which has 3 input fields :
<input type="text" name="foo[10]" value="a" />
<input type="text" name="foo[22]" value="b" />
<input type="text" name="foo[35]" value="c" />
How do I access it as request.POST['foo'][22]
instead of request.POST['foo[22]']
Django does not offer such parsing of POST data out of the box.
You will have to do parsing yourself. You can check what DRF does for that: https://github.com/encode/django-rest-framework/blob/master/rest_framework/utils/html.py#L15
I guess I’ll revert to :
<input type="text" name="age" value="a" />
<input type="text" name="age" value="b" />
<input type="text" name="age" value="c" />
and ages= request.POST.getlist('age')