forms ModelChoiceField queryset + extra choice fields django forms

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?


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)

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