基于Django的租车Web应用执行migrate时出现datetime类型错误求助
TypeError: fromisoformat: argument must be str After Removing DateTime Fields Let's break down why you're hitting this error and how to fix it quickly:
What's Causing the Issue?
Even though you removed datetime-related code from your models.py, the old migration files still contain references to those fields with invalid configurations. Specifically, look at your first migration file:
migrations.AddField( model_name='cart', name='renting_date', field=models.DateTimeField(default=1), preserve_default=False, ),
You set default=1 for a DateTimeField—Django tries to parse this integer as an ISO datetime string, which fails with the fromisoformat: argument must be str error you're seeing. The migration system doesn't care that you removed the field from your model later; it tries to run all existing migrations in order.
Step-by-Step Fixes
Option 1: Reset Migrations (Best for Development, No Critical Data)
If you're still in development and don't have important data in your database, this is the quickest way:
- Delete all files in your
app/migrationsfolder except__init__.py. - Delete your database file (e.g.,
db.sqlite3for SQLite). - Regenerate fresh initial migrations:
python manage.py makemigrations - Apply the new migrations:
python manage.py migrate
Option 2: Fix Existing Migrations (For When You Can't Lose Data)
If you need to keep your database data, edit the problematic migration files:
- Open the first migration file with the
renting_datefield. Either:- Replace
default=1with a valid datetime default (likedefault=django.utils.timezone.now—don't forget to addimport django.utils.timezoneat the top of the migration file), or - Delete the entire
AddFieldoperation forrenting_date(since you removed this field from your model anyway).
- Replace
- Remove any other migration operations that reference fields you've deleted (like the second migration altering
renting_datetoDateField, and the third addingordered_datetoOrderPlacedif that field is gone from your model). - Run the migration again:
python manage.py migrate
Verify the Fix
After applying either option, run:
python manage.py showmigrations
You should see all migrations marked as applied, and running your app shouldn't show any "pending migrations" warnings anymore.
Pro Tip for Future Development
Django migrations are meant to be immutable once applied (especially in production). If you experiment with fields and decide to remove them, either:
- Delete the unapplied migration files immediately before running
migrate, or - Generate a reverse migration to remove the field properly with
python manage.py makemigrations --empty appthen writing the removal logic.
内容的提问来源于stack exchange,提问作者Rushikesh Lakhotiya

