开发者

forms ModelChoiceField queryset + extra choice fields django forms

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(querys开发者_Python百科et = 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


It appears that you just want to allow those form fields to be optional. Don't make it hard on yourself. See the documentation regarding marking a form field as required.

lead = forms.ModelChoiceField(queryset=People.objects.filter(poc__in=('lead', 'sr.lead')), required=False)


Do you have a Person object with pk 'None'?

i think you should be using

self.fields['lead'] = forms.ModelChoiceField(queryset = Pepole.objects.filter(poc__in       = ('lead','sr.lead')), empty_label="None")
self.fields['lead2'] = forms.ModelChoiceField(queryset = Pepole.objects.filter(role__in = ('lead','sr.lead')), empty_label="None")

edit:

Since you are using a modelchoicefield, i would think that all your choices would be either of that model type or none.

You can "extend" the choices of that type by modifying the queryset you pass into the constructor for the modlechoicefield, e.g.:

qs = People.objects.filter(poc__in = ('lead','sr.lead'))
ext = People.objects.filter(role__in = ('lead', 'sr.lead'))

qs = qs | ext

self.fields['lead'] = forms.ModelChoiceField(queryset = qs, empty_label='None')
or for updating
self.fields['lead'].queryset = qs

this question talks about the modelchoicefield a bit and might be of interest to you:

How do I filter ForeignKey choices in a Django ModelForm?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜