[Python] Django Datetime TypeError: fromisoformat: argument must be str

Discussão em 'Python' iniciado por Stack, Março 27, 2025.

  1. Stack

    Stack Membro Participativo

    I am having this error while using django. I try to get the date that one transaction happened but i get this error:

    > E:\1. APP\finance_app>docker-compose exec web python manage.py migrate
    Operations to perform:
    Apply all migrations: admin, auth, contenttypes, finance, sessions
    Running migrations:
    Applying finance.0004_investment_pnl_investment_total_worth...Traceback (most recent call last):
    File "/app/manage.py", line 22, in <module>
    main()
    File "/app/manage.py", line 18, in main
    execute_from_command_line(sys.argv)
    File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line
    utility.execute()
    File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
    File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 413, in run_from_argv
    self.execute(*args, **cmd_options)
    File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 459, in execute
    output = self.handle(*args, **options)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 107, in wrapper
    res = handle_func(*args, **kwargs)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/migrate.py", line 357, in handle
    post_migrate_state = executor.migrate(
    ^^^^^^^^^^^^^^^^^
    File "/usr/local/lib/python3.11/site-packages/django/db/migrations/executor.py", line 135, in migrate
    state = self._migrate_all_forwards(
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/usr/local/lib/python3.11/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards
    state = self.apply_migration(
    ^^^^^^^^^^^^^^^^^^^^^
    File "/usr/local/lib/python3.11/site-packages/django/db/migrations/executor.py", line 255, in apply_migration
    state = migration.apply(state, schema_editor)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/usr/local/lib/python3.11/site-packages/django/db/migrations/migration.py", line 132, in apply
    operation.database_forwards(
    File "/usr/local/lib/python3.11/site-packages/django/db/migrations/operations/fields.py", line 110, in database_forwards
    schema_editor.add_field(
    File "/usr/local/lib/python3.11/site-packages/django/db/backends/base/schema.py", line 722, in add_field
    definition, params = self.column_sql(model, field, include_default=True)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/usr/local/lib/python3.11/site-packages/django/db/backends/base/schema.py", line 383, in column_sql
    " ".join(
    File "/usr/local/lib/python3.11/site-packages/django/db/backends/base/schema.py", line 330, in _iter_column_sql
    default_value = self.effective_default(field)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/usr/local/lib/python3.11/site-packages/django/db/backends/base/schema.py", line 483, in effective_default
    return field.get_db_prep_save(self._effective_default(field), self.connection)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/usr/local/lib/python3.11/site-packages/django/db/models/fields/__init__.py", line 1008, in get_db_prep_save
    return self.get_db_prep_value(value, connection=connection, prepared=False)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/usr/local/lib/python3.11/site-packages/django/db/models/fields/__init__.py", line 1677, in get_db_prep_value
    value = self.get_prep_value(value)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/usr/local/lib/python3.11/site-packages/django/db/models/fields/__init__.py", line 1655, in get_prep_value
    value = super().get_prep_value(value)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/usr/local/lib/python3.11/site-packages/django/db/models/fields/__init__.py", line 1531, in get_prep_value
    return self.to_python(value)
    ^^^^^^^^^^^^^^^^^^^^^
    File "/usr/local/lib/python3.11/site-packages/django/db/models/fields/__init__.py", line 1616, in to_python
    parsed = parse_datetime(value)
    ^^^^^^^^^^^^^^^^^^^^^
    File "/usr/local/lib/python3.11/site-packages/django/utils/dateparse.py", line 114, in parse_datetime
    return datetime.datetime.fromisoformat(value)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    TypeError: fromisoformat: argument must be str


    here is the code that raises the error:

    class Transaction(models.Model):

    TRANSACTION_TYPES = (
    ('income', 'Income'),
    ('expense', 'Expense'),
    )

    RECURRENCE_TYPES = (
    ('daily', 'Daily'),
    ('weekly', 'Weekly'),
    ('biweekly', 'Bi-Weekly'),
    ('monthly', 'Monthly'),
    )

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    transaction_type = models.CharField(max_length=7, choices=TRANSACTION_TYPES)
    amount = models.DecimalField(max_digits=10, decimal_places=2)
    description = models.CharField(max_length=255)
    category = models.CharField(max_length=255, blank=True, null=True) # Optional category field
    recurrence = models.CharField(max_length=10, choices=RECURRENCE_TYPES, blank=True, null=True) # Recurrence rule
    next_due_date = models.DateField(blank=True, null=True) # The next date when this transaction will be added
    transaction_date = models.DateTimeField(default=timezone.now)


    def __str__(self):
    # Check if transaction_date is set and valid before formatting
    if self.transaction_date:
    return f"{self.transaction_type} of {self.amount} on {self.transaction_date}"
    else:
    return f"{self.transaction_type} of {self.amount}"

    def save(self, *args, **kwargs):
    print(f"Saving transaction_date: {self.transaction_date}")
    if self.recurrence and not self.next_due_date:
    # Set the next_due_date based on the recurrence type
    if self.recurrence == 'daily':
    self.next_due_date = self.transaction_date.date() + timedelta(days=1)
    elif self.recurrence == 'weekly':
    self.next_due_date = self.transaction_date.date() + timedelta(weeks=1)
    elif self.recurrence == 'biweekly':
    self.next_due_date = self.transaction_date.date() + timedelta(weeks=2)
    elif self.recurrence == 'monthly':
    self.next_due_date = self.transaction_date.date().replace(month=self.transaction_date.month+1) # Simplified monthly logic
    super().save(*args, **kwargs)


    Here is also my already made transactions.:

    [{"id":1,"user":1,"transaction_type":"expense","amount":"33.00","description":"Cosmote","category":null,"recurrence":null,"next_due_date":null,"transaction_date":"2025-03-26T14:03:02.430961Z"},{"id":2,"user":1,"transaction_type":"income","amount":"1000.00","description":".","category":"Salary","recurrence":"monthly","next_due_date":"2025-03-03","transaction_date":"2025-03-26T14:03:02.430961Z"},{"id":3,"user":1,"transaction_type":"income","amount":"1000.00","description":".","category":"Salary","recurrence":"monthly","next_due_date":"2025-03-03","transaction_date":"2025-03-26T14:03:02.430961Z"},{"id":4,"user":1,"transaction_type":"income","amount":"450.00","description":"Rent","category":"Rent","recurrence":"biweekly","next_due_date":"2025-03-01","transaction_date":"2025-03-26T14:03:02.430961Z"}]


    last here is the migration 0004 look like:

    # Generated by Django 5.1.6 on 2025-02-20 12:43

    from django.db import migrations, models


    class Migration(migrations.Migration):

    dependencies = [
    ('finance', '0003_rename_amount_investment_purchase_price_and_more'),
    ]

    operations = [
    migrations.AddField(
    model_name='investment',
    name='pnl',
    field=models.DateTimeField(default=0.0),
    ),
    migrations.AddField(
    model_name='investment',
    name='total_worth',
    field=models.DateTimeField(default=0.0),
    ),
    ]


    last migration i did:

    # Generated by Django 5.1.6 on 2025-03-26 14:21

    import django.utils.timezone
    from django.db import migrations, models


    class Migration(migrations.Migration):

    dependencies = [
    ('finance', '0028_transaction_transaction_date'),
    ]

    operations = [
    migrations.AlterField(
    model_name='transaction',
    name='transaction_date',
    field=models.DateTimeField(default=django.utils.timezone.now),
    ),
    ]


    i can't understand the reason why is this happening i tried using directly timezone.now():

    transaction_date = timezone.now()


    instead of transaction_date = models.DateTimeField(default=timezone.now) but it got the same error, also tries using if else statement to check in the str function but nothing last i tried using this format in str

    return f"{self.transaction_type} of {self.amount} on {self.transaction_date}"
    return f"{self.transaction_type} of {self.amount} on {self.transaction_date.strftime('%B %d, %Y')}"


    any idea why may this is happening?

    update: here is also the code of class investment where i tried to calculate the investment a user has made live using api i have created a total_worth and pnl field that in reality i did not need so i commented it out but at first i made the migration and after i commented i also migrate again.

    class Investment(models.Model):
    name = models.CharField(max_length=100) # e.g., Bitcoin, Tesla
    symbol = models.CharField(max_length=10, unique=True) # e.g., BTC, TSLA
    quantity = models.DecimalField(max_digits=10, decimal_places=4 , default=0.0) # Number of shares/coins
    purchase_price= models.DecimalField(max_digits=10, decimal_places=2) # Price at purchase
    current_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) # Real-time price
    investment_type = models.CharField(max_length=20, choices=[('Stock', 'Stock'), ('Crypto', 'Crypto')])

    last_updated = models.DateTimeField(default=timezone.now, null=True , blank=True)

    #total_worth = models.DecimalField(max_digits=15 , decimal_places=4 , default=0.0)
    #pnl = models.DecimalField(max_digits=15 ,decimal_places=4 , default=0.0)

    def __str__(self):
    return f"{self.name} ({self.symbol}) - {self.quantity} units"


    def total_worth(self):
    """Total worth of this investment"""
    return self.quantity * self.current_price if self.current_price else Decimal('0.0')

    def pnl(self):
    """Profit and Loss calculation"""
    return (self.current_price - self.purchase_price) * self.quantity if self.current_price else Decimal('0.0')

    # Automatically calculate total worth and PnL when saving
    """def update_total_worth(self):
    self.total_worth = self.amount_invested * self.current_price
    self.save()
    """
    def save(self, *args, **kwargs):
    #self.total_worth = self.current_price * self.quantity if self.current_price else 0.0
    #self.pnl = self.total_worth - (self.purchase_price * self.quantity)
    super().save(*args, **kwargs) # Call the original save method

    Continue reading...

Compartilhe esta Página