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

问题描述

我正在尝试在从查询集中加载的 ModelChoiceField 中创建一个表单,我想向 ModelChoiceField 添加一些自定义值以进行扩展我使用了选择字段,如下所示,但在更新表单时,出现以下错误

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.

代码:

 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?

推荐答案

那行不通.看看 ModelChoiceField 是如何工作的:

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.

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

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 查询集 + 额外的选择字段 Django 表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-29 22:41