django 2.1复选框

时间:2018-10-23 08:05:02

标签: django python-3.x

请帮助...。我是django的新手 保存“选择有效的选择。['DST','DAB','CGAA']不是可用的选择之一。”时,我在POST方法上始终收到此错误。“这是我的代码;

models.py

class research_data(models.Model):
      sourcefund_choices = (
        ('DPCIE','DOST-PCIEERD'),
        ('DPCAA','DOST-PCIEERD'),
        ('DST','DOST'),
        ('CHD','CHED'),
        ('DA','DA'),
        ('DAB','DA-BAR'),
        ('CGAA','CSU-GAA(fund 101)'),
        ('C164','CSU(fund 164)'),
        )
      source_fund = models.TextField(blank=True,choices=sourcefund_choices)
      amt_granted = models.IntegerField(blank=True)
      status_res = models.CharField(max_length=20,choices=status_choices)
      date_start = models.DateField(blank=True,default=timezone.now)
      date_completed = models.DateField(blank=True,default=timezone.now)

forms.py

class ktmform_main(forms.ModelForm):
      class Meta:
           fields = {
              'source_fund',
              'amt_granted',
              'status_res',
              'date_start',
              'date_completed',
           }
           widgets = {
              'source_fund': forms.CheckboxSelectMultiple(attrs={'class':'filled-in','id':'sf'}),
              'amt_granted': forms.NumberInput(attrs={'class':'validate','id':'amtg'}),
              'status_res': forms.Select(),
              'date_start': forms.TextInput(attrs={'class':'datepicker','id':'dst'}),
              'date_completed': forms.TextInput(attrs={'class':'datepicker','id':'dcm'}),
           }

views.py

def res_add(request):
    if request.method=='GET':
        ktmfrm = forms.ktmform_main()
        args = {
            'ktmfrm':ktmfrm,
        }
        return render(request,'IMS/Res_Form.html',args)
    else:
        ktmfrm = forms.ktmform_main(request.POST,request.FILES)
        if ktmfrm.is_valid():
            ktmfrm.save()
            ktmfrm=ktmform_main()
            args = {
            'ktmfrm':ktmfrm,
            'stat':'saved',
            }
            return render(request,'IMS/Res_Form.html',args)
        else:
            args = {
            'ktmfrm':ktmfrm,
            'stat':'failed',
            }
            return render(request,'IMS/Res_Form.html',args)

“ source_fund”是CheckboxSelectMultiple作为表单小部件的字段

1 个答案:

答案 0 :(得分:0)

这是添加多个选择字段的简便方法

django-multiselectfield

from multiselectfield import MultiSelectField

source_fund = models.MultiSelectField(choices=sourcefund_choices, blank=True, max_choices='x')