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

Django技术问题:复选框数据存入数据库及forms与models区别

解决复选框数据存入数据库(选中存1/未选中存0)及Django forms.py与models.py区别

一、实现复选框选中/未选中状态存入数据库

1. 定义数据库模型(models.py)

先创建对应模型存储每个复选框的状态,用IntegerField存储1(选中)或0(未选中):

from django.db import models

class ReportSettings(models.Model):
    executive_summary = models.IntegerField(default=0)
    scope = models.IntegerField(default=0)
    isms = models.IntegerField(default=0)
    methodology = models.IntegerField(default=0)
    recommendation = models.IntegerField(default=0)

    def __str__(self):
        return "Report Settings"

执行迁移命令生成数据库表:

python manage.py makemigrations
python manage.py migrate

2. 修改视图逻辑(views.py)

通过映射关系判断每个选项的选中状态,对应设置1或0并保存到数据库:

from django.shortcuts import render
from .models import ReportSettings

def checkbox(request):
    # 复选框value与模型字段的映射表
    checkbox_mapping = {
        'Executive_summary': 'executive_summary',
        'Scope': 'scope',
        'ISMS': 'isms',
        'Methodology': 'methodology',
        'Recommendation': 'recommendation'
    }

    if request.method == 'POST':
        selected_values = request.POST.getlist('checkbox_data')
        # 确保只存在一条设置记录(可根据实际需求调整,比如关联用户)
        settings, created = ReportSettings.objects.get_or_create(pk=1)
        
        # 遍历所有选项,设置1/0状态
        for checkbox_val, model_field in checkbox_mapping.items():
            setattr(settings, model_field, 1 if checkbox_val in selected_values else 0)
        
        settings.save()

    # 获取当前设置,用于模板回显选中状态
    current_settings = ReportSettings.objects.filter(pk=1).first() or ReportSettings()
    return render(request, 'checkbox.html', {'current_settings': current_settings})

3. 更新模板(checkbox.html)

添加回显逻辑,根据数据库值给复选框设置checked属性:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Checkbox</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
    <div class="form-check">
        <h5>Checkbox_report</h5>
        <input type="checkbox" value="Executive_summary" id="Executive_summary" name="checkbox_data" 
               {% if current_settings.executive_summary == 1 %}checked{% endif %}>
        <label for="Executive_summary"> Executive summary &nbsp</label>
        
        <input type="checkbox" value="Scope" id="Scope" name="checkbox_data" 
               {% if current_settings.scope == 1 %}checked{% endif %}>
        <label for="Scope"> Scope &nbsp</label>
        
        <input type="checkbox" value="ISMS" id="ISMS" name="checkbox_data" 
               {% if current_settings.isms == 1 %}checked{% endif %}>
        <label for="ISMS"> ISMS &nbsp</label>
        
        <input type="checkbox" value="Methodology" id="Methodology" name="checkbox_data" 
               {% if current_settings.methodology == 1 %}checked{% endif %}>
        <label for="Methodology"> Methodology &nbsp</label>
        
        <input type="checkbox" value="Recommendation" id="Recommendation" name="checkbox_data" 
               {% if current_settings.recommendation == 1 %}checked{% endif %}>
        <label for="Recommendation"> Recommendation &nbsp</label>
    </div>
 <button type="submit">submit</button>
</form>
</body>
</html>

二、forms.py与models.py的主要区别

models.py

  • 核心作用:定义数据库结构,是Django ORM的核心,将Python类映射为数据库表,类属性对应表字段。
  • 职责:处理数据持久化,定义数据类型、约束(默认值、是否为空)以及数据关联关系(一对一、一对多等)。
  • 示例:上面的ReportSettings类就是模型,直接对应数据库中的一张表,每个属性对应表中的列。

forms.py

  • 核心作用:处理用户输入表单,负责表单渲染(生成HTML元素)、数据验证(检查输入格式、长度等),将表单数据转换为Python对象。
  • 职责:作为用户与模型的交互层,简化表单创建与验证,可通过ModelForm自动关联模型生成表单。
  • 示例:用ModelForm绑定ReportSettings模型,能自动生成对应字段的表单,自带数据验证逻辑。

核心差异

  • models是数据层:管数据存储的结构、规则;
  • forms是交互层:管用户输入的合法性、表单的渲染与数据流转。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 02:10:25