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">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        {% load static %}
        <script src="{% static 'jquery-3.6.2.min.js' %}" ></script>
    </head>
    
    <body>
        <form action="{% url 'index' %}" method="post">
            {% csrf_token %}
            <button id="button1" name="action" value="">button2</button>
            <script>
                $("#button1").click(
                    function(){
                        arr = ["one", "two"]
                        $("#button1").attr('value',arr)
                    }
                )
            </script>
        </form>
    </body>

</html>

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

JavaScript


<script>
  $("#button1").click(
    function(){
      arr = JSON.stringify(["one", "two"])
      $("#button1").attr('value',arr)
    })
</script>

Python


import json


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

Note:

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