Issue
I want to make multithreaded transactions in django, when the payment of one user is divided between the second and third user in different proportions. I wrote the code. It works for two users, and when a third user appears, an error appears, although the code is exactly the same as for two users. my views.py:
@transaction.atomic()
def transaction_file(request):
if request.method == "POST":
try:
buyer = request.POST.get('buyer')
seller = request.POST.get('seller')
admin = request.POST.get('admin')
amount = request.POST.get('amount')
buyer_obj = UserBalanceChange.objects.get(user = buyer)
seller_obj = UserBalanceChange.objects.get(user=seller)
admin_obj = UserBalanceChange.objects.get(user=admin)
with transaction.atomic():
buyer_obj.amount -= int(0.8*int(amount))
buyer_obj.save()
seller_obj.amount += int(0.8*int(amount))
seller_obj.save()
with transaction.atomic():
buyer_obj.amount -= int(0.2 * int(amount))
buyer_obj.save()
admin_obj = admin_obj + int(0.2 * int(amount))
admin_obj.save()
# messages.success(request, 'Транзакция успешно проведена')
return HttpResponse('Транзакция успешно проведена')
except Exception as e:
print(e)
# messages.success(request,'Что-то пошло не так!(')
return HttpResponse('Что-то пошло не так!(')
return render(request,'chat/files/chattransaction.html')
my models.py
class UserBalanceChange(models.Model):
user = models.ForeignKey(User,on_delete = models.CASCADE, related_name='balance_changes')
amount = models.DecimalField(verbose_name='Amount', default=0, max_digits=18, decimal_places=2)
datetime = models.DateTimeField(verbose_name='date', default=timezone.now)
def __str__(self):
return f'{self.user.username}'
my html:
<form method="POST" style="width: 50%;">
{% csrf_token %}
<form method="post">
<div class="form-group">
<label>Покупатель</label>
<input class="form-control" name="buyer" type="text" placeholder="Покупатель">
</div>
<div class="form-group">
<label>Продавец</label>
<input class="form-control" name="seller" type="text" placeholder="Продавец">
</div>
<div class="form-group">
<label>Админ</label>
<input class="form-control" name="admin" type="text" placeholder="Админ">
</div>
<div class="form-group">
<label>Цена</label>
<input class="form-control" name="amount" type="text" placeholder="Цена">
</div>
<button type="submit" class="btn btn-primary">Купить</button>
</form>
Solution
The error is probably on your line:
admin_obj = admin_obj + int(0.2 * int(amount))
You are trying to add to the object instead of the amount
field of the object.
Answered By - Nathan Roberts
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.