“'int'对象没有属性'save'”从views.py更新模型

时间:2019-05-07 19:45:20

标签: django python-3.x django-models django-views

我想在views.py中更新用户模型。有没有办法做到这一点?我想做的是减去views.py中的用户点,并更新为没有表单的模型。但这给了我“'int'对象没有属性'save'”

views.py

    def buy_item(request, item_name):
        item = ShopItem.objects.get(item_name=item_name)
        price = item.item_price
        user = request.user
        user_point = user.point
        if user_point >= price:
            user_point = user_point - price
            point_left = user_point
            point_left.save()
            msg = messages.success(request, 'You bought item!')
            return redirect('/shop', msg)
        else:
            msg = messages.success(request, 'You do not have enough point')

        context = ({
            'point': user_point,
            'item': item,
            'form': form
        })

        return render(request, 'item.html', context)

项目模型。py

class ShopItem(models.Model):
    item_name = models.CharField(max_length=16)
    item_image = models.ImageField(upload_to='media_items')
    item_description = models.CharField(max_length=255)
    item_command = models.CharField(max_length=255)
    item_price = models.IntegerField(default=0)

    def __str__(self):
        return self.item_name

    def snippet(self):
        return self.item_description[:45]

用户模型.py

class UserProfile(AbstractUser):
    username = models.CharField(max_length=16, unique=True)
    email = models.EmailField(default='', unique=True)
    phone = models.CharField(max_length=10)
    point = models.IntegerField(default=0)
    password1 = models.CharField(max_length=255)
    password2 = models.CharField(max_length=255)

    USERNAME_FIELD = 'username'

我要保存的是更改后的点。

我该怎么办?请帮忙!我真的是新来的。对不起,我的英语。

1 个答案:

答案 0 :(得分:0)

遗憾的是,我没有足够的声誉来发表评论,但是您需要在模型中而不是在Integer中使用save()方法。

因此,您应该替换

point_left = user_point
point_left.save()

为此

user.point = user_point # Assign the new point to the user
user.save() # Update your user model