[英]Error when field is left empty: invalid literal for int() with base 10
I am saving a new article in the database. 我正在数据库中保存新文章。 Here is a simplified script that I use:
这是我使用的简化脚本:
class Article(models.Model):
name = models.CharField(max_length=255)
rating = models.PositiveSmallIntegerField(blank=True, null=True)
Then here is how I try to create a new record: 然后是我尝试创建新记录的方法:
article = Article(
name = request.POST['name'],
rating = request.POST['rating'],
)
article.save()
The problem, however, is that the rating is not always set. 但是,问题在于,并非总是设置等级。 The field can be null, so that is no problem.
该字段可以为null,因此没有问题。 However, at the moment if the field is left empty, it returns an error: invalid literal for int() with base 10.
但是,如果此字段现在为空,则返回错误:以10为底的int()的无效文字。
I would like to basically say: 我想基本上说:
I'm new to Python and not sure how to achieve this. 我是Python的新手,不确定如何实现这一点。
The easiest way is to catch the error and then set the value to None in an except block. 最简单的方法是捕获错误,然后在except块中将其值设置为None。
try:
rating = int(request.POST['rating'])
except ValueError:
rating = None
article = Article(
name = request.POST['name'],
rating = rating,
)
article.save()
Assuming POST
is a dictionary (I forget, it's been a while), then you can one-liner it with something like this: 假设
POST
是一本字典(我忘记了,已经有一段时间了),那么您可以使用以下内容将其一字排开:
rating = int(request.POST.get('rating', -1))
if rating == -1:
rating = None
or 要么
try:
rating = int(request.POST['rating'])
except:
rating = None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.