Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(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?

like image 398
sush Avatar asked Mar 12 '11 07:03

sush


People also ask

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

How do you make a field optional in django?

If you want to allow blank values in a date field (e.g., DateField , TimeField , DateTimeField ) or numeric field (e.g., IntegerField , DecimalField , FloatField ), you'll need to use both null=True and blank=True . Show activity on this post. Use null=True and blank=True in your model.

What is the difference between form and ModelForm in django?

The differences are that ModelForm gets its field definition from a specified model class, and also has methods that deal with saving of the underlying model to the database. Show activity on this post. Show activity on this post. Form is a common form that is unrelated to your database (model ).


1 Answers

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
like image 142
Yuji 'Tomita' Tomita Avatar answered Oct 23 '22 15:10

Yuji 'Tomita' Tomita