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

从HTML日期选择器取值并保存至Django后端模型的实现问题

解决点击提交按钮后将日期选择器值保存到Django后端的问题

一、前端代码问题与修正

核心问题点

  • 事件监听绑定错误:将submit事件绑在了日期输入框上,输入框不会触发该事件,应绑定到提交按钮的click事件
  • JavaScript变量名与赋值错误:未正确给定义的对象赋值,且未定义Django POST请求必需的CSRF令牌
  • 缺少基础校验:未判断用户是否选择了日期

修正后的vieworders.html代码

<div class="row mb-4">
    <label for="dropOffDate">Drop Off Date Selector:</label>
    <br>
    <input type="date" id="dropOffDate" min="2022-01-01" max="3000-12-31">
    <button type="button" value="Continue" class="btn btn-outline-danger" id="submit-drop-off-date">Submit Drop Off Date</button>
</div>

<script type="text/javascript">
    // 从Django Cookie中提取CSRF令牌
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    const csrftoken = getCookie('csrftoken');

    const dateInput = document.getElementById("dropOffDate");
    const submitBtn = document.getElementById("submit-drop-off-date");

    // 绑定按钮点击事件
    submitBtn.addEventListener('click', function(e){
        e.preventDefault();
        submitDropOffData();
        console.log("Drop off data submitted...");
    });

    function submitDropOffData() {
        // 校验日期是否选择
        if (!dateInput.value) {
            alert("请选择日期!");
            return;
        }

        const dropOffDateInformation = {
            'dropOffDate': dateInput.value
        };

        const url = "/process_drop_off_date/";
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrftoken,
            }, 
            body: JSON.stringify({'dropoffDate': dropOffDateInformation}),
        })
        .then((response) => {
            if (!response.ok) throw new Error('请求失败');
            return response.json();
        })
        .then((data) => {
            console.log('Drop off date has been submitted...');
            alert('Drop off date submitted');
            window.location.href = "{% url 'home' %}";
        })
        .catch((error) => {
            console.error('提交失败:', error);
            alert('提交失败,请重试');
        });
    }
</script>

二、后端视图问题与修正

核心问题点

  • 未限制请求方法:应只处理POST请求
  • 取值路径错误:未对应前端传递的JSON结构
  • 缺少异常处理:未捕获数据缺失、数据库操作失败等异常

修正后的views.py代码

import json
from django.http import JsonResponse
from .models import DropOffDate

def processDropOffDate(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            drop_off_date = data['dropoffDate']['dropOffDate']
            
            DropOffDate.objects.create(
                DropOffDate=drop_off_date
            )
            
            return JsonResponse({'message': 'Drop off date submitted...'}, safe=False)
        except KeyError:
            return JsonResponse({'error': '缺少必要的日期数据'}, status=400)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)
    else:
        return JsonResponse({'error': '仅支持POST请求'}, status=405)

三、模型优化建议

模型字段名不符合Python PEP8命名规范(推荐小写加下划线),优化后代码如下:

class DropOffDate(models.Model):
    drop_off_date = models.DateField()

    def __str__(self):
        return str(self.drop_off_date)

若修改字段名,需同步更新视图中的创建代码:

DropOffDate.objects.create(
    drop_off_date=drop_off_date
)

额外注意事项

  • 确保urls.py中已配置/process_drop_off_date/路由,指向processDropOffDate视图
  • 日期选择器返回的YYYY-MM-DD格式与DjangoDateField原生兼容,无需额外转换
  • 新增的前后端校验与异常处理可提升代码健壮性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 06:09:24