javascript - 如何根据复选框输入启用 django 表单字段?
问题描述
这是我的 django 动态表单,它根据给定的 csv 文件列生成字段。
class SetFeatureForm(forms.Form):
def __init__(self, project=None, *args, **kwargs):
super(SetFeatureForm, self).__init__(*args, **kwargs)
if project:
choices = [(column,column) for column in pd.read_csv(project.file.path).columns]
self.fields['feature'] = forms.MultipleChoiceField(choices=choices, required=True, )
self.fields['feature'].widget.attrs['size']=len(choices)
for _,choice in choices:
self.fields[choice] = forms.ChoiceField( choices=DATA_TYPE.items())
我必须启用基于字段“功能”的所有字段,即 MultipleChoiceField。根据选择,我必须启用“选择”字段。我该怎么做,提前谢谢。
解决方案
不确定您正在寻找什么,但如果您需要将动态选择输入模型的能力:
模型.py
def get_menu_choices():
choices_tuple = []
#do your stuff
return choices_tuple
class ChoiceModel(models.Model):
choices_f = models.CharField(max_length=8, blank=True)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._meta.get_field('choices_f')._choices = lazy(get_menu_choices, list)()
def get_absolute_url(self):
return reverse('testapp:choicemodel_list')
否则,如果您已经知道标题并且它们是静态的,您可以关注https://docs.djangoproject.com/en/2.1/ref/models/fields/#choices
只需确保将您的表单修改为:forms.py
class ChoiceForm(forms.ModelForm):
class Meta():
model = ChoiceModel
fields = ['choices_f']
顺便说一句,上述动态解决方案来自http://blog.yawd.eu/2011/allow-lazy-dynamic-choices-djangos-model-fields/
推荐阅读
- cloudera - 哪个 Cloudera 版本支持 YARN 节点标签
- html - 即使包含 Bootstrap 也无法正常工作
- sql - 到达日期时如何使特定行过期?
- php - 如何根据自定义分类法、开始日期和结束日期在 wordpress 中使用搜索输入来获取帖子?
- php - 在 Woocommerce 中根据购物车重量添加自定义结帐字段
- python - strptime 字符串到日期时间对象的转换
- linux - Linux 共享库依赖于 dlopen 使用 RTLD_LOCAL 打开的另一个共享库中的符号
- angular - 最简单的输出绑定测试不起作用
- angular - 将 Angular CLI 升级到 8
- java - 使用带有 StretchIcon (ImageIcon) 的 JPanel.setLocation 时出现堆栈溢出错误