我有一个 2.2 Django 项目,其中包含
django-otp==0.8.0
、django-two-factor-auth[phonenumbers]==1.14.0
,以及一个使用这两个库的应用程序 two_factor_auth
。
当测试通过迁移运行时,它们会通过:
$ ./manage.py test two_factor_auth
Applying two_factor.0001_initial... OK
Applying two_factor.0002_auto_20150110_0810... OK
Applying two_factor.0003_auto_20150817_1733... OK
Applying two_factor.0004_auto_20160205_1827... OK
Applying two_factor.0005_auto_20160224_0450... OK
Applying two_factor.0006_phonedevice_key_default... OK
Applying two_factor.0007_auto_20201201_1019... OK
----------------------------------------------------------------------
Ran 13 tests in 5.549s
OK
请注意,这些迁移是来自
django-two-factor-auth
包的迁移,因为 two-factor-auth
应用程序没有迁移。
但是,当在没有迁移的情况下运行测试时(如在 CI 和本地环境中所做的那样,因为我们的项目有数百个迁移),它们会失败:
$ ./manage.py test two_factor_auth --nomigrations
Traceback (most recent call last):
File "/opt/miniconda3/lib/python3.8/site-packages/two_factor/views/profile.py", line 38, in get_context_data
'default_device': default_device(self.request.user),
File "/opt/miniconda3/lib/python3.8/site-packages/two_factor/utils.py", line 16, in default_device
for device in devices_for_user(user):
File "/opt/miniconda3/lib/python3.8/site-packages/django_otp/__init__.py", line 80, in devices_for_user
for device in model.objects.devices_for_user(user, confirmed=confirmed):
File "/opt/miniconda3/lib/python3.8/site-packages/django/db/models/query.py", line 274, in __iter__
self._fetch_all()
...
File "/opt/miniconda3/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: two_factor_phonedevice
我可以确认,如果我重新使用
django-otp==0.7.5
和 django-two-factor-auth==1.9.1
,这个问题就不再出现。
可能是什么问题?
您可以按照以下步骤解决该错误。 *我使用 django-two-factor-auth 1.15.4.
首先,使用以下命令取消迁移
two_factor
:
python manage.py migrate two_factor zero
然后,删除虚拟环境中的
0001_squashed_0008_delete_phonedevice.py
和 0008_delete_phonedevice.py
:
two_factor
└-migrations
|-0001_initial.py
|-0001_squashed_0008_delete_phonedevice.py # Delete
|-0002_auto_20150110_0810.py
|-0003_auto_20150817_1733.py
|-0004_auto_20160205_1827.py
|-0005_auto_20160224_0450.py
|-0006_phonedevice_key_default.py
|-0007_auto_20201201_1019.py
└-0008_delete_phonedevice.py # Delete
最后,使用以下命令迁移
two_factor
:
python manage.py migrate two_factor
请小心,如果您使用以下命令压缩迁移并迁移
two_factor
,则会出现错误,所以不要这样做:
python manage.py squashmigrations two_factor 0007_auto_20201201_1019
python manage.py migrate two_factor
two_factor
└-migrations
|-0001_initial.py
|-0001_squashed_0007_auto_20201201_1019.py # Error
|-0002_auto_20150110_0810.py
|-0003_auto_20150817_1733.py
|-0004_auto_20160205_1827.py
|-0005_auto_20160224_0450.py
|-0006_phonedevice_key_default.py
└-0007_auto_20201201_1019.py