Search code examples
pythondjangodjango-modelsdjango-rest-frameworkdjango-views

How to only let user transfer funds from wallet which belongs to his account in django?


models.py

from django.db import models
from django.contrib.auth.models import User
from djmoney.models.fields import MoneyField

# Create your models here.
class Account(models.Model):
    # ACCOUNT_TYPES = (
    #     ('PERSONAL', 'PERSONAL'),
    #     ('BUSINESS', 'BUSINESS')
    # )

    account_owner = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    account_number = models.CharField(max_length=15, unique=True)

    # account_type = models.CharField(max_length=17, choices=ACCOUNT_TYPES)
    balance = models.DecimalField(max_digits=5, decimal_places=3)

    date_created = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return self.account_number


class Transaction(models.Model):
    account_owner = models.OneToOneField(User, on_delete=models.CharField, null=True)
    from_account = models.CharField(max_length=15)

    to_account = models.CharField(max_length=15)
    amount = models.DecimalField(max_digits=5, decimal_places=3)

    timestamp = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return str(self.amount)



views.py

@login_required
def transfer(request):
    if request.method == "POST":
        form = forms.TransactionForm(request.POST)
        if form.is_valid():
            sender = models.Account.objects.get(account_number=request.POST.get('from_account'))
            if sender.balance > decimal.Decimal(request.POST.get('amount')):
                trans = form.save()
                trans.account_owner = request.user

                # debit the sender account
                sender.balance -= decimal.Decimal(request.POST.get('amount'))
                sender.save()

                # credit receiver account
                receiver = models.Account.objects.get(account_number=request.POST.get('to_account'))
                receiver.balance += decimal.Decimal(request.POST.get('amount'))
                receiver.save()

                return render(request, "wallet.html")


    else:
        form = forms.TransactionForm()
        return render(request, "wallet.html", {'form': form})

Hi, I am having trouble with this, transferring funds from one account to another is working great but I only want the user's account number to be able to transfer who is logged in...not this that I can input anyone's account number and transfer from one account to another...I just want to make sure the account number belongs to the user logged in and only that is the from_account. Thanks! I really need help on this.


Solution

  • Assuming you have a functioning authentication system, you can: try: Account.objects.get(account_number=request.POST.get('from_account'), account_owner=request.user) except Account.DoesNotExist: # you should be catching this anyway in case form_account is wrong raise ValidationError("some error message") To make things cleaner, look into how you can relay the validation logic to the django form you are using. `