Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用自定义字段时不保存Django表单_Python_Django - Fatal编程技术网

Python 使用自定义字段时不保存Django表单

Python 使用自定义字段时不保存Django表单,python,django,Python,Django,我正在写一份django GiftCardReceive,除了在增加我的giftcard价值后,其他一切都有效,我无法保存价值 class GiftCardRedeem(FormView): model = GiftCard form_class = GiftCardCheck template_name = 'site/redeem.html' success_url = '/settings/redeem' def form_valid(self,

我正在写一份django GiftCardReceive,除了在增加我的giftcard价值后,其他一切都有效,我无法保存价值

class GiftCardRedeem(FormView):
    model = GiftCard
    form_class = GiftCardCheck
    template_name = 'site/redeem.html'
    success_url = '/settings/redeem'

    def form_valid(self, form):
        MessageForm = form.save(commit=False)
        one_entry = GiftCard.objects.get(code=form.cleaned_data['code'])
        currentbal = self.request.user.userprofile.balance
        totalbal = int(currentbal) + int(one_entry.worth)
        print self.request.user.userprofile.balance
        totalbal.save()
错误:

'int' object has no attribute 'save'

.save()用于保存对象,而不是对象/单个字段的一部分。不要试图保存值-将值添加到用户对象,然后保存该值

但是我想将值添加到userprofile余额中,而不是将任何内容添加到giftcard对象中,然后将余额添加到用户并保存-这里的问题是,您正在对非对象的对象调用对象方法。您通过查询user:currentbal=self.request.user.userprofile.balance这样您就有了一个用户模型和一个具有余额的userprofile(可能是一个模型)。因此,您需要将user.userprofile.balance设置为totalbal,然后保存user.currentbal=self.request.user.userprofile.balance currentbal.save()给出错误“'unicode'对象没有属性'save'”,这是因为您从用户处获取余额并试图保存它。您需要执行类似于
user.userprofile.currentbal.save()或
user.userprofile.balance=totalbal user.userprofile.save()的操作