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

如何获取HTML开关checkbox的当前状态并将布尔值传递给Django

实现方案

1. 前端获取开关状态并提交

checkbox的checked属性原生返回布尔值,刚好对应你需要的true/false格式,不用额外转换。

方式1:AJAX异步提交(推荐)

无需刷新页面即可提交数据,适配大部分场景:

// 获取两个开关的当前状态
const commentNotify = document.getElementById('new_comment_on_my_article').checked;
const forumNotify = document.getElementById('new_answer_on_my_forum_thread').checked;
// 从模板生成的csrf隐藏域取令牌(Django POST请求必须携带)
const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;

// 提交请求
fetch('/你的Django接口路径/', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': csrfToken
    },
    body: JSON.stringify({
        new_comment_on_my_article: commentNotify,
        new_answer_on_my_forum_thread: forumNotify
    })
}).then(res => res.json()).then(data => {
    // 自定义提交成功后的逻辑
    console.log('设置保存成功', data);
})

记得在对应HTML模板里加Django的CSRF生成标签:

{% csrf_token %}

方式2:普通表单同步提交

如果不需要异步效果,可修改原有HTML结构,适配表单默认提交逻辑:

<form method="post" action="/你的Django接口路径/">
    {% csrf_token %}
    <div class="tab-pane fade" id="account-notifications">
        <div class="card-body pb-2">
            <h6 class="mb-4">Activity</h6>
            <div class="form-group">
                <label class="switcher">
                    <!-- 加同名隐藏域,未选中时默认提交false -->
                    <input type="hidden" name="new_comment_on_my_article" value="false">
                    <input type="checkbox" class="switcher-input" name="new_comment_on_my_article" id="new_comment_on_my_article" checked value="true">
                    <span class="switcher-indicator">
                        <span class="switcher-yes"></span>
                        <span class="switcher-no"></span>
                    </span>
                    <span class="switcher-label">Email me when someone comments on my article</span>
                </label>
            </div>
            <div class="form-group">
                <label class="switcher">
                    <!-- 第二个开关同理加隐藏域 -->
                    <input type="hidden" name="new_answer_on_my_forum_thread" value="false">
                    <input type="checkbox" class="switcher-input" name="new_answer_on_my_forum_thread" id="new_answer_on_my_forum_thread" value="true">
                    <span class="switcher-indicator">
                        <span class="switcher-yes"></span>
                        <span class="switcher-no"></span>
                    </span>
                    <span class="switcher-label">Email me when someone answers on my forum thread</span>
                </label>
            </div>
        </div>
    </div>
    <button type="submit">保存设置</button>
</form>

2. 后端Django接收处理

对应AJAX JSON提交的处理逻辑

import json
from django.http import JsonResponse

def save_notification_settings(request):
    if request.method == 'POST':
        # 解析JSON请求体
        req_data = json.loads(request.body)
        comment_notify = req_data.get('new_comment_on_my_article', False)
        forum_notify = req_data.get('new_answer_on_my_forum_thread', False)
        
        # 此处写你的业务逻辑,比如将设置保存到用户表
        # request.user.notify_comment = comment_notify
        # request.user.notify_forum = forum_notify
        # request.user.save()
        
        return JsonResponse({'code': 0, 'msg': '保存成功'})

对应普通表单提交的处理逻辑

from django.http import JsonResponse
from django.shortcuts import redirect

def save_notification_settings(request):
    if request.method == 'POST':
        comment_notify = request.POST.get('new_comment_on_my_article') == 'true'
        forum_notify = request.POST.get('new_answer_on_my_forum_thread') == 'true'
        
        # 同上处理业务逻辑
        
        # 可返回JSON或跳转页面
        # return redirect('/settings/')
        return JsonResponse({'code': 0, 'msg': '保存成功'})

注意事项

  • 未选中的checkbox默认不会被带入普通表单的提交参数,因此必须添加同名隐藏域默认传false,避免后端取值异常
  • CSRF令牌是Django POST请求的必填项,缺失会返回403错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 08:36:04