Reputation: 11118
I have a choice field in a form defined as
REFERRAL_CHOICES = (
(None, 'Please choose'),
('search', 'From a search engine'),
('social', 'From a social network'),
)
referral_source = forms.ChoiceField(
choices=REFERRAL_CHOICES
)
I also have a clean_company_size
function which checks if the field is set to a good value:
def clean_company_size(self):
company_size = self.cleaned_data.get('company_size', None)
if company_size is None:
raise ValidationError('Please select a company size')
return company_size
If I add a or company_size == 'None'
condition to the above None check, all works well. However, I am curious why the None value is being cast to a string. What is the best way of accomplishing a default prompts in a choice field and having that field be required?
Upvotes: 1
Views: 1853
Reputation: 5048
All POST
and GET
variables, as well as Select
HTML tag values are initially sent as strings. Django converts them to -say- int
when it is deductable from the model. In your case it is not possible to distinguish a "None" string from a "None" object, they are both possible values. You may prefer using "" instead of None
in your REFERRAL_CHOICHES
Upvotes: 1