You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中如何通过request.POST传递列表类型数据?

问题描述

在Django项目中,我有如下HTML代码:

<!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>

点击按钮后,通过jQuery把数组arr赋值给按钮的value属性,提交表单后得到的request.POST结果是:

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

我期望得到的是'action': ['one', 'two']或者'action': [['one', 'two']],请问该怎么实现?

解决方案

方法1:动态添加多隐藏字段(得到['one', 'two'])

浏览器会自动把按钮的value转为字符串(数组会变成逗号分隔的格式),要传递多个独立值,最好给数组每个元素添加一个同名隐藏字段:

<!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" id="myForm">
            {% csrf_token %}
            <button id="button1" type="submit">button2</button>
            <script>
                $("#button1").click(function(e){
                    e.preventDefault(); // 先阻止默认提交行为
                    const arr = ["one", "two"];
                    // 清除之前可能存在的同名隐藏字段
                    $('input[name="action"]').remove();
                    // 给每个数组元素创建隐藏字段
                    arr.forEach(item => {
                        $('<input>').attr({
                            type: 'hidden',
                            name: 'action',
                            value: item
                        }).appendTo('#myForm');
                    });
                    // 手动提交表单
                    $("#myForm").submit();
                });
            </script>
        </form>
    </body>
</html>

后端获取时,必须用request.POST.getlist('action'),会直接得到['one', 'two'];如果直接用request.POST['action']只会拿到最后一个元素。

方法2:序列化为JSON字符串(得到嵌套数组格式)

如果想要把整个数组作为一个整体传递,先把数组转成JSON字符串,后端再解析还原:

<!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(){
                    const arr = ["one", "two"];
                    // 把数组转为JSON字符串赋值给按钮value
                    $("#button1").attr('value', JSON.stringify(arr));
                });
            </script>
        </form>
    </body>
</html>

后端处理代码:

import json

def index(request):
    if request.method == 'POST':
        action_str = request.POST.get('action')
        action_list = json.loads(action_str)  # 得到 ['one', 'two']
        # 如果需要嵌套数组格式,就包装一下:action_nested = [action_list]
    # 后续业务逻辑

这样POST数据里的action是['["one","two"]'],解析后就能还原成原数组,按需包装成嵌套格式即可。

方法3:用Django表单组件(推荐规范写法)

如果是正规Django开发,建议用Django自带的表单类来处理多值提交,比如MultipleChoiceField:

  1. 先在forms.py里定义表单:
from django import forms

class ActionForm(forms.Form):
    action = forms.MultipleChoiceField(choices=[('one', 'one'), ('two', 'two')], required=False)
  1. 前端模板代码:
<!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 %}
            {{ form.as_p }}
            <button id="button1" type="submit">button2</button>
            <script>
                $("#button1").click(function(e){
                    e.preventDefault();
                    const arr = ["one", "two"];
                    // 勾选对应的选项
                    arr.forEach(item => {
                        $(`input[name="action"][value="${item}"]`).prop('checked', true);
                    });
                    // 提交表单
                    $('form').submit();
                });
            </script>
        </form>
    </body>
</html>
  1. 后端视图处理:
from .forms import ActionForm

def index(request):
    if request.method == 'POST':
        form = ActionForm(request.POST)
        if form.is_valid():
            action_list = form.cleaned_data['action']  # 直接得到 ['one', 'two']
    else:
        form = ActionForm()
    return render(request, 'your_template.html', {'form': form})

这种方法更符合Django的开发规范,还能自动处理数据验证。


内容的提问来源于stack exchange,提问作者Vasilii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 12:15:31