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?
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.
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.
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 ).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With