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:
我还有一个clean_company_size函数,它检查字段是否设置为一个好的值:
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?
如果我在上面的None检查中添加了a或company_size =='None'条件,则一切正常。但是,我很好奇为什么将None值转换为字符串。在选择字段中完成默认提示并且需要该字段的最佳方法是什么?
1 个解决方案
#1
1
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
所有POST和GET变量以及Select HTML标记值最初都以字符串形式发送。当Django可以从模型中删除时,它们将它们转换为-say-int。在您的情况下,无法区分“无”字符串和“无”对象,它们都是可能的值。您可能更喜欢在REFERRAL_CHOICHES中使用“”而不是“None”
#1
1
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
所有POST和GET变量以及Select HTML标记值最初都以字符串形式发送。当Django可以从模型中删除时,它们将它们转换为-say-int。在您的情况下,无法区分“无”字符串和“无”对象,它们都是可能的值。您可能更喜欢在REFERRAL_CHOICHES中使用“”而不是“None”