我正在尝试创建一个表单,ModelChoiceField从queryset加载,我想为ModelChoiceField添加一些自定义值,我已经使用了选择字段,如下所示,但在更新表单时,得到以下错误
表格错误:
选择一个有效的选择.这种选择不是可用的选择之一.
代码:
- self.fields['lead'] = forms.ModelChoiceField(queryset = Pepole.objects.filter(poc__in = ('lead','sr.lead')))
- self.fields['lead2'] = forms.ModelChoiceField(queryset = Pepole.objects.filter(role__in = ('lead','sr.lead')))
- choice_field = self.fields['lead']
- choice_field.choices = list(choice_field.choices) + [('None','None')]
- choice_field = self.fields['lead2']
- choice_field.choices = list(choice_field.choices) + [('None','None')]
我在这做错了吗?
解决方法
那不行.看看ModelChoiceField的工作原理:
- try:
- key = self.to_field_name or 'pk'
- value = self.queryset.get(**{key: value})
- except self.queryset.model.DoesNotExist:
- raise ValidationError(self.error_messages['invalid_choice'])
- return value
请改用ChoiceField并自定义处理数据.
- class TestForm(forms.Form):
- mychoicefield = forms.ChoiceField(choices=QS_CHOICES)
- def __init__(self,*args,**kwargs):
- super(TestForm,self).__init__(*args,**kwargs)
- self.fields['mychoicefield'].choices = \
- list(self.fields['mychoicefield'].choices) + [('new stuff','new')]
- def clean_mychoicefield(self):
- data = self.cleaned_data.get('mychoicefield')
- if data in QS_CHOICES:
- try:
- data = MyModel.objects.get(id=data)
- except MyModel.DoesNotExist:
- raise forms.ValidationError('foo')
- return data