【问题标题】:Django throwing "invalid literal for int() with base 10: ''" when trying to save object attributeDjango在尝试保存对象属性时抛出“invalid literal for int() with base 10: ''”
【发布时间】:2012-01-30 22:36:12
【问题描述】:

当我尝试保存添加的两个对象属性时,Django 不断抛出以下内容。

invalid literal for int() with base 10: ''

观点是:

def buy_pack(request, pack_name):
if request.method == 'POST':
    form = CardForm(request.POST, request.user)
    pack = Pack.objects.get(name=pack_name)
    stripe_user = request.user.username

    if form.is_valid():
        token = request.POST['stripeToken']
        charge = stripe.Charge.create(
            amount=pack.cost,
            currency="usd",
            card=token,
            description=stripe_user+"_"+pack.name,
        )

        datestring = charge.created
        dt = datetime.datetime.fromtimestamp(float(datestring))
        new_purchase = Purchase(user=request.user, date_time=dt, pack=pack, payment_id=charge.id, last_4_digits=charge.card.last4)
        new_purchase.save()

        user_profile = request.user.get_profile()
        t = user_profile.videos_remaining + pack.videos_allowed
        user_profile.videos_remaining = t
        user_profile.save()

有问题的模型是:

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    name = models.CharField(max_length=50)
    videos_remaining = models.IntegerField(default=1)
    last_4_digits = models.IntegerField(max_length=4, blank=True)
    stripe_id = models.CharField(max_length=255, blank=True)

    def __unicode__(self):
        return self.name

还有:

class Pack(models.Model):
    name = models.CharField(max_length=25)
    videos_allowed = models.IntegerField()
    cost = models.IntegerField()

    def __unicode__(self):
        return self.name

追溯是:

Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/Users/Jeff/Dropbox/xxxxx/Code/thankyouvid/../thankyouvid/main/views.py" in buy_pack
  48.           user_profile.save()
File "/Library/Python/2.7/site-packages/django/db/models/base.py" in save
  460.         self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/Library/Python/2.7/site-packages/django/db/models/base.py" in save_base
  526.                         rows = manager.using(using).filter(pk=pk_val)._update(values)
File "/Library/Python/2.7/site-packages/django/db/models/query.py" in _update
  491.         return query.get_compiler(self.db).execute_sql(None)
File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
  869.         cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
  725.             sql, params = self.as_sql()
File "/Library/Python/2.7/site-packages/django/db/models/sql/compiler.py" in as_sql
  834.                 val = field.get_db_prep_save(val, connection=self.connection)
File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner
  28.             return func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner
  28.             return func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_save
  276.         return self.get_db_prep_value(value, connection=connection, prepared=False)
File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner
  53.             return func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py" in inner
  53.             return func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py" in get_db_prep_value
  271.             value = self.get_prep_value(value)
File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_value
  876.         return int(value)

Exception Type: ValueError at /buy_pack/most/
Exception Value: invalid literal for int() with base 10: ''

作为参考,user_profile.videos_remaining 的存储值为 1,pack.videos_allowed 的存储值为 100。我希望它将这两个值相加并将它们作为 101 存储在 user_profile.videos_remaining 对象属性中。

如果您能提供任何帮助,我将不胜感激。

编辑:问题最终是我没有为整数字段 last_4_digits 传递值。如果您有一个带有 blank=True 的 integerField 并且不为其提交值,似乎会发生这种情况。

【问题讨论】:

    标签: django


    【解决方案1】:

    问题最终是我没有为整数字段 last_4_digits 传递值。如果您有一个带有 blank=True 的 integerField 并且不为其提交值,似乎会发生这种情况。

    【讨论】:

    • 问题是当你有blank = True 时,django 将存储并返回一个空字符串(我假设你的卡模型将它存储为字符串)'' 这就是你想要的作为整数传入。您可以通过在 Python shell 中执行 int('') 得到相同的错误。
    • @slipnslide21 我试图理解这一点。如果一个 IntegerField 有空白=True,那么它不是必须为其提交一个值,不是吗?
    • 其实,现在明白了。 @Burhan Khalid 的详细回复 (stackoverflow.com/a/20399819/1526703) 帮助了
    【解决方案2】:

    我在 Django 填充脚本中也遇到了此错误消息,其中 ForeignKey 同时具有 blank=Truenull=True,并通过 '' 作为objects.get_or_create() 的参数。

    我通过传递argument=None 解决了这个问题。 None 部分是线索。

    【讨论】:

    • 我在人口脚本中遇到了完全相同的问题。谢谢。
    【解决方案3】:

    当“整数”输入包含空值或字符串值(如“'id'”、“'.'.”等)时,会发生这种类型的错误。 所以,你必须找出你得到的这种类型的输入。

    【讨论】:

      【解决方案4】:

      我的问题是我使用的required=False, disabled=True, 没有将数据发送到该字段的服务器。我改成

      amount_payments = CharField(widget=TextInput(attrs={'readonly': 'readonly'}))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-25
        • 2019-02-28
        • 2022-01-09
        • 2019-04-16
        相关资源
        最近更新 更多