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

求助:解决Django中views.py出现的KeyError问题

问题解决建议

核心原因分析

错误KeyError: 'email'直接表明后端从POST的JSON数据中无法找到email字段,导致服务器抛出500错误。主要问题出在前端表单提交逻辑和后端容错处理两方面。

具体修复步骤

1. 修复HTML表单的字段缺失问题

你提供的HTML邮箱输入框只有id属性,没有name属性。表单提交时,浏览器会根据name属性识别字段并传递值,没有name的字段不会被提交。修改HTML代码:

<p>
<label for="email">Email: </label>
<input type="email" placeholder="Your email" maxlength="200" required="" id="email" name="email">
</p>

同时检查其他表单字段(比如first_name、phone_number等)是否都添加了对应的name属性,确保所有需要的字段都能被提交。

2. 后端添加字段容错处理

直接用data['key']取值会在字段缺失时抛出KeyError,应该改用get()方法,并对缺失字段返回明确的错误提示:

import json
from django.http import HttpResponse
from django.core import serializers
from datetime import datetime
from .models import Reservation

@csrf_exempt
def bookings(request):
    if request.method == 'POST':
        try:
            data = json.load(request)
        except json.JSONDecodeError:
            return HttpResponse(json.dumps({'error': '无效的JSON数据'}), content_type='application/json', status=400)
        
        # 检查必填字段是否存在
        required_fields = ['first_name', 'phone_number', 'email', 'reservation_date', 'reservation_slot']
        missing_fields = [field for field in required_fields if field not in data]
        if missing_fields:
            return HttpResponse(
                json.dumps({'error': f'缺少必填字段: {", ".join(missing_fields)}'}),
                content_type='application/json',
                status=400
            )
        
        exist = Reservation.objects.filter(
            reservation_date=data['reservation_date'],
            reservation_slot=data['reservation_slot']
        ).exists()
        if not exist:
            booking = Reservation(
                name=data['first_name'],
                phone_number=data['phone_number'],
                email=data['email'],
                reservation_date=data['reservation_date'],
                reservation_slot=data['reservation_slot'],
            )
            booking.save()
            return HttpResponse(json.dumps({'success': 1}), content_type='application/json')
        else:
            return HttpResponse(json.dumps({'error': '该时段已被预订'}), content_type='application/json')
    
    # GET请求逻辑保持不变
    date = request.GET.get('date', datetime.today().date())
    bookings = Reservation.objects.filter(reservation_date=date)
    booking_json = serializers.serialize('json', bookings)
    return HttpResponse(booking_json, content_type='application/json')

3. 修复模型中的潜在错误

你的Reservation模型的__str__方法引用了self.surname,但模型中并没有surname字段,会导致后续调用__str__时出错,修改为:

def __str__(self):
    return self.name

或者如果需要姓氏字段,在模型中添加surname = models.CharField(max_length=100)。

4. 优化电话号码字段类型

phone_number使用IntegerField不合理:电话号码可能包含前导零、加号或超过整数存储范围,建议改为CharField:

phone_number = models.CharField(max_length=20)

额外注意事项

  • 前端发送POST请求时,确保请求头设置为Content-Type: application/json,并且正确将表单数据序列化为JSON格式(比如用JSON.stringify())。
  • 避免使用csrf_exempt,生产环境中建议在前端表单中添加{% csrf_token %},并确保请求携带CSRF令牌。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 02:02:01