gpt4 book ai didi

django - 如何在南迁中访问 auth User 的 User.objects.create_user(...) ?

转载 作者:行者123 更新时间:2023-12-03 03:03:33 24 4
gpt4 key购买 nike

我没有使用 django 的 auth 模块,而是使用了自己的模块,并且已经非常后悔了。

为了纠正这种情况,我正在尝试将数据从我的 User 模型迁移到 django.auth.models.User。

我创建了一个数据迁移,如下所示:

def forwards(self, orm):
"""Migrate user information from mooi User model to auth User model."""

OldUser = orm['mooi.User']
User = orm['auth.User']
Profile = orm['mooi.Profile']

oldUsers = OldUser.objects.all()
for oldUser in oldUsers:
newUser = User.objects.create_user(username=oldUser.id, email=oldUser.email, password=oldUser.password)
# ...more irrelevant code follows...

当我运行迁移时,我收到此错误(回溯):

#...irrelevant traceback precedes...
File "[projdir]/mooi/migrations/0005_from_mooi_users_create_auth_users_with_profiles.py", line 18, in forwards
newUser = User.objects.create_user(username=oldUser.id, email=oldUser.email, password=oldUser.password)
File "[virtual_env_dir]lib/python2.6/site-packages/south/orm.py", line 397, in __getattr__
return getattr(self.real, name)
AttributeError: 'Manager' object has no attribute 'create_user'

经过进一步调查,我发现所引用的 Manager 的时间是 south.orm.NoDryRunManager,这解释了该错误。

现在,我需要 create_user 的原因是创建 django.contrib.auth 能够理解的密码哈希。

说了这么多,我该怎么做呢?考虑到我所处的困境,最优雅的解决方案是什么?!

提前致谢。

更新1

根据stevejalim的建议,我尝试使用 Userset_password(...) 如下:

newUser.set_password(raw_password=oldUser.password)
newUser.save()

但是失败并出现此错误:

File "[projdir]/mooi/migrations/0005_from_mooi_users_create_auth_users_with_profiles.py", line 21, in forwards
newUser.set_password(raw_password=oldUser.password)
AttributeError: 'User' object has no attribute 'set_password'

我确实在 south documentation 中找到了提示其中指出:

South doesn’t freeze every aspect of a model; for example, it doesn’t preserve new managers, or custom model methods, as these would require serialising the python code that runs those method (and the code that depends on, and so forth).

If you want custom methods in your migration, you’ll have to copy the code in, including any imports it relies on to work. Remember, however, for every import that you add, you’re promising to keep that import valid for the life for the migration.

我想问题仍然存在,最好/最安全的方法是什么?复制 set_password(...) 方法?创建一个为我散列密码的函数?还有其他想法吗?

最佳答案

为什么你不直接导入你需要的东西?
我遇到了同样的问题,我所做的是:

from django.contrib.auth.hashers import make_password

class Migration(DataMigration):
...

def forwards(self, orm):
user = orm['auth.User'].objects....
user.password = make_password('123')
...

关于django - 如何在南迁中访问 auth User 的 User.objects.create_user(...) ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3291556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com