Reputation: 734
I have a select menu in Django built like this in models.py.
execution_time = models.IntegerField(
choices=((i, i) for i in (0, 15, 30, 45, 60)),
blank=False,
default=30,
verbose_name='estimated time'
)
I also have a text field(which will appear when a user selects 0 as option in execution_time) in forms.py and clean method.
class DummyForm(forms.ModelForm):
admin_time = forms.CharField(
help_text=_('Enter If more than 60 minutes.'),
required=False,
widget=forms.TextInput(attrs={'class': 'fill-width'}))
def clean(self):
cleaned_data = super(DummyForm, self).clean()
admin_time = cleaned_data.get('admin_time')
if admin_time:
cleaned_data['execution_time'] = admin_time
return cleaned_data
The value of select option(execution_time) gets overrided by admin_time. But it's not getting validated. Since i just have 15,30,45,60 in the select menu. Also, I can't remove the select option. How should I change the validation so that I don't get error like "Value 80 is not a valid choice".
Upvotes: 1
Views: 1891
Reputation: 13731
The validation that's errorring out is at the model level and not the form level. You need to set the choices available to the user at the form level and allow the model to accept any number on the model.
class ExampleModel(models.Model):
execution_time = models.IntegerField(
blank=False,
default=30,
verbose_name='estimated time'
)
class DummyForm(models.ModelForm):
admin_time = forms.IntegerField(
help_text=_('Enter If more than 60 minutes.'),
required=False,
widget=forms.TextInput(attrs={'class': 'fill-width'}))
execution_time = forms.IntegerField(
widget=forms.Select(choices=((i, i) for i in (0, 15, 30, 45, 60)))
def clean(self):
cleaned_data = super(DummyForm, self).clean()
admin_time = cleaned_data.get('admin_time')
if admin_time:
cleaned_data['execution_time'] = admin_time
return cleaned_data
Upvotes: 1