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

如何在Django中获取选中的单选按钮值并存入模型?

解决Django单选按钮提交请假类型的问题

问题根源

你的代码存在两个关键问题:

  1. HTML中的单选按钮缺少value属性,导致表单提交时无法传递选中的请假类型标识
  2. 视图函数错误地尝试获取reason1-reason5这些键,但所有单选按钮的name都是reason,因此提交后只会在request.POST中出现reason键,对应选中项的value值

修正后的HTML代码

给每个单选按钮添加value属性(建议使用简短标识符,和Django模型的选项对应):

<div class="col">
  <div class="form-group">
    <input class="form-check-input" type="radio" name="reason" id="reason1" value="casual_leave" checked>
    <label class="form-check-label" for="reason1">
      Casual Leave
    </label>
  </div>
  <div class="form-group">
    <input class="form-check-input" type="radio" name="reason" id="reason2" value="medical_leave">
    <label class="form-check-label" for="reason2">
        Medical Leave
    </label>
  </div>
  <div class="form-group">
    <input class="form-check-input" type="radio" name="reason" id="reason3" value="earned_leave">
    <label class="form-check-label" for="reason3">
        Earned Leave
    </label>
  </div>
  <div class="form-group">
    <input class="form-check-input" type="radio" name="reason" id="reason4" value="office_duty">
    <label class="form-check-label" for="reason4">
        Office Duty
    </label>
  </div>
  <div class="form-group">
    <input class="form-check-input" type="radio" name="reason" id="reason5" value="compensatory_off">
    <label class="form-check-label" for="reason5">
        Compensatory Off
    </label>
  </div>
</div>

简化后的视图函数

直接获取选中的reason值,无需逐个判断ID:

from django.http import HttpResponse
# 导入你的模型,示例:from .models import LeaveApplication

def leaveapplicationsubmit(request):
    if request.method == 'POST':
        # 获取选中的请假类型值
        selected_reason = request.POST.get('reason')
        
        # 验证是否选中了选项
        if not selected_reason:
            return HttpResponse('Please select the reason')
        
        # (可选)如果需要将标识符转为显示文本,可使用映射表
        reason_map = {
            'casual_leave': 'Casual Leave',
            'medical_leave': 'Medical Leave',
            'earned_leave': 'Earned Leave',
            'office_duty': 'Office Duty',
            'compensatory_off': 'Compensatory Off'
        }
        display_reason = reason_map.get(selected_reason, 'Unknown')
        
        # 将数据存入Django模型(示例)
        # LeaveApplication.objects.create(
        #     reason=selected_reason,
        #     user=request.user  # 假设用户已登录
        # )
        
        return HttpResponse(f'Successfully submitted leave request for {display_reason}')
    else:
        return HttpResponse("Failed")

推荐的Django模型设计

使用choices字段约束请假类型,让数据更规范:

from django.db import models
from django.contrib.auth.models import User

class LeaveApplication(models.Model):
    # 定义请假类型选项,和HTML中的value对应
    REASON_CHOICES = [
        ('casual_leave', 'Casual Leave'),
        ('medical_leave', 'Medical Leave'),
        ('earned_leave', 'Earned Leave'),
        ('office_duty', 'Office Duty'),
        ('compensatory_off', 'Compensatory Off'),
    ]
    
    reason = models.CharField(max_length=50, choices=REASON_CHOICES)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='leave_applications')
    submitted_at = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return f"{self.user.username} - {self.get_reason_display()}"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 03:45:37