形式ModelChoiceField queryset +额外的选择字段django表单 [英] forms ModelChoiceField queryset + extra choice fields django forms

查看:239
本文介绍了形式ModelChoiceField queryset +额外的选择字段django表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个FormChoiceField中的表单,从查询集加载,我想添加几个自定义值到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 ','无')]

我在这里做错什么?

解决方案

这不行。看看 ModelChoiceField 的工作原理:

  try:
key = self.to_field_name或'pk'
value = self.queryset.get(** {key:value})
除了self.queryset.model.DoesNotExist:
raise ValidationError(self .error_messages ['invalid_choice'])
返回值

您无法随机添加东西给它



使用 ChoiceField ,并自定义处理数据。




$ b def __init __(self,* args,...) ** kwargs)
super(TestForm,self).__ init __(* args,** kwargs)
self.fields ['mychoicefield']。choices = \
list(self。字段['mychoicefield']。选择)+ [('new stuff','new')]

def clean_mychoicefield(self):
data = self.cleaned_data.get('mychoicefield ')
如果QS_CHOICES中的数据:
尝试:
data = MyModel.objects.get(id = data)
除了MyModel.DoesNotExist:
raise forms.ValidationError ('foo')
返回数据


I am trying to create a form in that ModelChoiceField loads from queryset and i want add few custom values to ModelChoiceField for extend i have used choice field, like below but while updating the form,getting below error

Form Error : Select a valid choice. That choice is not one of the available choices.

Code :

 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')]

Am i doing any thing wrong here?

解决方案

That's not going to work. Look at how a ModelChoiceField works:

    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

You can't add something randomly to it.

Use a ChoiceField instead and custom process the data.

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

这篇关于形式ModelChoiceField queryset +额外的选择字段django表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆