I have a django model, which has a int field (with null=True, blank=True). Now when I get a form submit from the user, I assign it like so:
我有一个django模型,它有一个int字段(null = True,blank = True)。现在当我收到用户提交的表单时,我会这样分配:
my_model.width= form.cleaned_data['width']
However sometimes I get an error:
但有时我会收到错误:
ValueError: invalid literal for int() with base 10: ''
I was wandering if it's the blank ('') string value that gets assigned to the field? Because my understanding was the model will treat blank string as null/blank?
如果它被分配给字段的空白('')字符串值,我在徘徊?因为我的理解是模型会将空字符串视为null / blank?
Any help would be appreciated in this matter. Thanks.
在这件事情上,任何帮助都会受到赞赏。谢谢。
1 个解决方案
#1
No, it doesn't. If you want to assign NULL, use Python's None
. Otherwise Django will try to parse a number from the string and that fails for the empty string.
不,它没有。如果要分配NULL,请使用Python的None。否则Django将尝试解析字符串中的数字,并且对于空字符串失败。
You can use the or
construct to achieve this:
您可以使用或构造来实现此目的:
my_model.width = form.cleaned_data['width'] or None
#1
No, it doesn't. If you want to assign NULL, use Python's None
. Otherwise Django will try to parse a number from the string and that fails for the empty string.
不,它没有。如果要分配NULL,请使用Python的None。否则Django将尝试解析字符串中的数字,并且对于空字符串失败。
You can use the or
construct to achieve this:
您可以使用或构造来实现此目的:
my_model.width = form.cleaned_data['width'] or None