Trying to find a way to pass a list to an item in request.POST. How do I do it?

This is my html code in django project:

<!DOCTYPE html> <html lang="en">
        <meta charset="UTF-8">
        {% load static %}
        <script src="{% static 'jquery-3.6.2.min.js' %}" ></script>
        <form action="{% url 'index' %}" method="post">
            {% csrf_token %}
            <button id="button1" name="action" value="">button2</button>
                        arr = ["one", "two"]


By clicking the button I run JQuery that assigns an array: arr to button1's value. This is request.POST afterwards:

<QueryDict: {'csrfmiddlewaretoken': ['Rws3PVVBVOGsoXm720M5YbuZNTYMin6CxklI78in2PWdrxAYKxw3XqV7cba2xt7P'], 'action': ['one,two']}>

Instead of 'action': ['one,two'] I want to get 'action': ['one', 'two'], or 'action': [['one', 'two']]

How do I do it?

Use JSON.stringify() to convert array into JSON string and then use json.loads(...) to load JSON string to convert it into Python object.

Your code will look like this


      arr = JSON.stringify(["one", "two"])


import json

def foo(request):
    action = request.POST.get('action')
    if action:
       print(json.loads(action)) # result -> {'action': ['one', 'two']}


Make sure you sanitize your request.POST.get('action') data it may contain malisious code if it's sent by client so always validate your request data.

Back to Top