表单ModelChoiceField查询集额外选择字段django表单

前端之家收集整理的这篇文章主要介绍了表单ModelChoiceField查询集额外选择字段django表单前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试创建一个表单,ModelChoiceField从queryset加载,我想为ModelChoiceField添加一些自定义值,我已经使用了选择字段,如下所示,但在更新表单时,得到以下错误

表格错误
选择一个有效的选择.这种选择不是可用的选择之一.

代码

  1. self.fields['lead'] = forms.ModelChoiceField(queryset = Pepole.objects.filter(poc__in = ('lead','sr.lead')))
  2. self.fields['lead2'] = forms.ModelChoiceField(queryset = Pepole.objects.filter(role__in = ('lead','sr.lead')))
  3. choice_field = self.fields['lead']
  4. choice_field.choices = list(choice_field.choices) + [('None','None')]
  5. choice_field = self.fields['lead2']
  6. choice_field.choices = list(choice_field.choices) + [('None','None')]

我在这做错了吗?

解决方法

那不行.看看ModelChoiceField的工作原理:
  1. try:
  2. key = self.to_field_name or 'pk'
  3. value = self.queryset.get(**{key: value})
  4. except self.queryset.model.DoesNotExist:
  5. raise ValidationError(self.error_messages['invalid_choice'])
  6. return value

您无法随机添加内容.

请改用ChoiceField并自定义处理数据.

  1. class TestForm(forms.Form):
  2. mychoicefield = forms.ChoiceField(choices=QS_CHOICES)
  3.  
  4. def __init__(self,*args,**kwargs):
  5. super(TestForm,self).__init__(*args,**kwargs)
  6. self.fields['mychoicefield'].choices = \
  7. list(self.fields['mychoicefield'].choices) + [('new stuff','new')]
  8.  
  9. def clean_mychoicefield(self):
  10. data = self.cleaned_data.get('mychoicefield')
  11. if data in QS_CHOICES:
  12. try:
  13. data = MyModel.objects.get(id=data)
  14. except MyModel.DoesNotExist:
  15. raise forms.ValidationError('foo')
  16. return data

猜你在找的HTML相关文章