Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError in views.py: type object 'Transaction' has no attribute 'objects'

Tags:

python

django

I have run into an issue using Django. I am creating a finance app which tracks deposits and withdrawals.Unfourtanently I have run into an issue using models. Here is the relevant code

Views.py

from django.shortcuts import render
from .models import Transaction

# Create your views here.
class Transaction:
    def __init__(self, name, description, location, amount):
        self.name = name
        self.description = description
        self.location = location
        self.amount = amount    

def sum(totals):
    sum = 0
    for i in range(len(totals)):
        if totals[i].name.lower() == 'deposit':
            sum += totals[i].amount
        else:
            sum -= totals[i].amount
    return sum


#transactions = [
#   Transaction('Deposit', 'Allowance', 'Home', 25.00),
#   Transaction('Withdrawl', 'Food', 'Bar Burrito', 11.90),
#   Transaction('Withdrawl', 'Snacks', 'Dollarama', 5.71)
#]



def index(request):
    transactions = Transaction.objects.all()
    balance = sum(transactions)
    return render(request, 'index.html', {'transactions':transactions,  'balance': balance})

Models.py

from django.db import models

# Create your models here.
class Transaction(models.Model):
    name = models.CharField(max_length = 100)
    description = models.CharField(max_length = 100)
    location = models.CharField(max_length = 100)
    amount = models.DecimalField(max_digits = 10, decimal_places = 2)

    def __str__(self):
        return self.name

admin.py

from django.contrib import admin
from .models import Transaction

# Register your models here.
admin.site.register(Transaction)

Let me know if there is any other code you need to look at and thanks in advance

like image 992
Khalid Talakshi Avatar asked Jun 23 '26 05:06

Khalid Talakshi


1 Answers

You don't need a second Transaction class in your views. It is shadowing the Transaction model/class imported from your model. Remove it!

More so, you also don't need a custom sum function, use the builtin sum:

def index(request):
    transactions = Transaction.objects.all()
    balance = sum(t.amount if t.name=='deposit' else -t.amount for t in transactions)
    ...
like image 134
Moses Koledoye Avatar answered Jun 25 '26 21:06

Moses Koledoye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!