如何根据Django表单单选按钮的选中值禁用另一组单选按钮选项
实现方案
不需要编写views层逻辑,核心联动功能通过前端JavaScript实现即可,建议补充Form层后端校验避免前端规则被绕过。
1. 模板侧添加联动逻辑
修改model_form_download.html,在原有表单代码后加入JS逻辑即可,以下是完整模板代码:
<form action="" name="" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Download"> </form> <script> // 获取两组单选按钮元素 const formatRadios = document.querySelectorAll('input[name="file_format"]'); const downloadRadios = document.querySelectorAll('input[name="file_download"]'); // 定义禁用规则:键为第一组单选的选中值,值为对应要禁用的第二组选项值列表 // 示例规则为:选中csv格式时,禁用两个带divide的下载选项,可根据自身需求修改 const disableRule = { 'csv': ['all_divide', 'unique_divide'] } // 联动更新第二组选项状态 function updateDownloadOptions() { const selectedFormat = document.querySelector('input[name="file_format"]:checked')?.value; const disabledOptions = disableRule[selectedFormat] || []; downloadRadios.forEach(radio => { radio.disabled = disabledOptions.includes(radio.value); // 若被禁用的选项之前处于选中状态,自动清空选中 if (radio.disabled && radio.checked) { radio.checked = false; } }) } // 页面初始化时执行一次 updateDownloadOptions(); // 绑定第一组单选的变化事件 formatRadios.forEach(radio => { radio.addEventListener('change', updateDownloadOptions); }) </script>
2. 可选:Form层补充后端校验
前端校验规则可被用户篡改绕过,建议在forms.py的DownloadForm类中补充和前端一致的校验逻辑,无需修改views代码,表单提交时会自动触发校验:
DOWNLOAD_CHOICES = [("all", "All values"), ("all_divide", "All values separated per IfcType"), ("unique", "Unique values"), ("unique_divide", "Unique values separated per IfcType")] FORMAT_CHOICES = [("xlsx", "Excel (.xlsx)"), ("csv", "comma-separated values (.csv)")] class DownloadForm(forms.Form): file_format = forms.ChoiceField(choices=FORMAT_CHOICES, widget=forms.RadioSelect()) file_download = forms.ChoiceField(choices=DOWNLOAD_CHOICES, widget=forms.RadioSelect()) def clean(self): cleaned_data = super().clean() file_format = cleaned_data.get('file_format') file_download = cleaned_data.get('file_download') # 校验规则和前端disableRule保持一致 if file_format == 'csv' and file_download in ['all_divide', 'unique_divide']: raise forms.ValidationError('CSV格式不支持当前选中的下载选项') return cleaned_data
内容的提问来源于stack exchange,提问作者Bruno_BNF
相关产品推荐
相关产品推荐

