def post(self, request, *args, **kwargs): post = self.get_object() if post.price > request.user.coin: return render(request, 'error.html', context={ 'errors': '你没有那么多金币啦!', 'return_url': reverse('archive:detail', kwargs=dict(pk=post.id)) }) request.user.coin -= post.price request.user.save() post.author.coin += post.price post.author.save() post.buyers.add(request.user) log_coin(-post.price, request.user.coin, None, request.user, '购买《%s》' % (post.title, )) log_coin(post.price, post.author.coin, None, post.author, '出售《%s》' % (post.title, )) return redirect('archive:detail', pk=post.id)
def form_valid(self, form): gift = get_object_or_404(models.Gift, show=True, pk=self.kwargs['gift_id']) return_url = reverse('archive:gift', kwargs=dict(pk=gift.id)) if gift.amount <= 0: return render(self.request, 'error.html', context={ 'errors': '没货了,请提醒管理员上货!', 'return_url': return_url }) if gift.price > self.request.user.coin: return render(self.request, 'error.html', context={ 'errors': '你没有那么多金币,快去提交贡献赚钱吧!', 'return_url': return_url }) self.object = form.save(commit=False) self.object.buyer = self.request.user self.object.gift = gift self.object.cost = gift.price self.object.save() self.request.user.coin -= gift.price self.request.user.save() gift.amount = F('amount') - 1 gift.save() log_coin(-gift.price, self.request.user.coin, None, self.request.user, "购买“%s”" % (gift.name, )) return redirect(self.get_success_url())