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

Django+AJAX提交表单触发MultiValueDictKeyError: 'category'问题求助

Django AJAX提交表单触发MultiValueDictKeyError: 'category'问题排查与解决

我尝试用Django+AJAX向数据库插入数据,不使用AJAX时表单提交正常,但用AJAX提交会报500错误,错误信息是MultiValueDictKeyError: 'category'。

相关代码

views.py

def post_order(request):
    if request.method == 'POST':
        
        order_id = request.POST['order_id']
        category = request.POST['category']
        product = request.POST['product']
        price_per_unit = request.POST['price_per_unit']
        quantity = request.POST['quantity']
        price_all = request.POST['price_all']

        new_order = PoductOrder(order_id=order_id, Category=Category.objects.get(name=category), 
        product=Product.objects.get(name=product), price_per_unit=price_per_unit, qantity=quantity, price_all=price_all )
        new_order.save()
        return HttpResponse('data has being saved')

post.js

$(document).on('submit', '#post_form', function(e){
    e.preventDefault();

    $.ajax({
        type:'POST',
        url:"/order/postorder",
        data:{
            order_id:$('#order_cart').val(),
            category:$('category').val(),
            product:$('#product').val(),
            price_per_unit:$('#per_unit').val(),
            quantity:$('#quantity').val(),
            price_all:$('#total').val(),
            csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),

        },
        success: function(data){
            alert(data);
        },
        error: function(error){
           console.log(error)
        }
    });
});

表单HTML

<div class="row">

            <form action="{% url 'post-order' %}" method="post" id="post_form">
                 {% csrf_token %} 
            <div class="col-sm-4">
                <div class="form-group">
                    <label class="control-label" for="order_id">Order ID</label>
                    <input type="text" name='order_id' class= 'form-control' id='order_cart' >

                </div>              
              </div>
            
            <div class="col-sm-4">
                <div class="form-group">
                    <label class="control-label" for="status">Product Category</label>
                    <select required name="category" id="category" class="form-control">
                        <option value="">--Select Product Category--</option>
                        {% for category in category %}
                    
                        <option value="{{ category.name }}">{{category.name }}</option>
                        {% endfor %}
                            </select>     
                                   </div>                
            </div>
            <div class="col-sm-4">
                <div class="form-group">
                    <label class="control-label" for="customer">Product</label>
                    <select required name="product" id="product" class="form-control">
                    <option value="">--Select Product--</option>  
                    {% for products in products %}
                    
                    <option value="{{ products.name }}">{{ products.name }}</option>
                    {% endfor %}
                        </select>
                </div>
            </div>
        </div>

错误追踪信息

Internal Server Error: /order/postorder
Traceback (most recent call last):
File "C:\Users\DELL\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\datastructures.py", line 84, in __getitem__
list_ = super().__getitem__(key)
^^^^^^^^^^^^^^^^^^^^^^^^
KeyError: 'category'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\DELL\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 56, in inner
response = get_response(request)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\DELL\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\DELL\Desktop\INVENTORY MANAGEMENT\dashboard\views.py", line 50,
in post_order
category = request.POST['category']
~~~~~~~~~~~~^^^^^^^^^^^^
File "C:\Users\DELL\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\datastructures.py", line 86, in __getitem__
raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'category'
[27/Apr/2023 11:44:48] "POST /order/postorder HTTP/1.1" 500 74249

解决方法

  • 核心问题修复:AJAX代码中获取category值的选择器遗漏了ID前缀#,原代码$('category').val()无法选中ID为category的下拉框,导致提交数据中缺失category字段,后端直接索引时抛出错误。将post.js中的该行改为$('#category').val()即可解决。
  • 额外优化建议:
    1. 后端获取POST数据时,改用request.POST.get('字段名', 默认值)替代直接索引,避免因字段缺失直接崩溃,比如category = request.POST.get('category'),必填校验可在前端或后端单独处理。
    2. 检查其他字段选择器(如#per_unit、#total)是否与HTML中的ID对应。
    3. 可在AJAX的error回调中打印error.responseText,获取更详细的后端报错信息。
    4. 修正模型字段拼写错误:代码中qantity应为quantity,避免数据库存储异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 14:53:10