user585936
user585936

Reputation:

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. However, at the moment if the field is left empty, it returns an error: invalid literal for int() with base 10.

I would like to basically say:

I'm new to Python and not sure how to achieve this.

Upvotes: 0

Views: 48

Answers (2)

UtahJarhead
UtahJarhead

Reputation: 2217

Assuming POST is a dictionary (I forget, it's been a while), then you can one-liner it with something like this:

rating = int(request.POST.get('rating', -1))
if rating == -1:
    rating = None

or

try:
    rating = int(request.POST['rating'])
except:
    rating = None

Upvotes: 1

CJR
CJR

Reputation: 3985

The easiest way is to catch the error and then set the value to None in an except block.

try:
    rating = int(request.POST['rating'])
except ValueError:
    rating = None

article = Article(
    name = request.POST['name'],
    rating = rating,
)
article.save()

Upvotes: 1

Related Questions