数据迁移导致错误 AttributeError: type object 'User' has no attribute 'normalize_username'?

3 python django data-migration

我正在尝试创建数据迁移以将用户添加到数据库。但是,当我尝试这样做时出现属性错误。

我已经运行 ipdb 来解决问题,我尝试注释掉用户对象的字段以查看其中之一是否导致错误,并且我尝试添加“user.save()”

# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2019-02-08 21:23
from __future__ import unicode_literals

from django.db import migrations
from django.conf import settings


def create_urechr_user(apps, schema_editor):
    staffPosition = apps.get_model("hr", "staffPosition")

    User = apps.get_model(settings.AUTH_USER_MODEL)
    user = User.objects.create_user(
        username = "myName",
        password = "test",
        is_active = True,
        email = "",
    )
    staff = staffPosition.objects.get(pk = 95)
    user.save()
    urec_staff = staffPosition.objects.create(
        parent_staff_position = staff,
        user_id = user,
        title = "My title here",
    )
    urec_staff.save()

class Migration(migrations.Migration):

    dependencies = [
        ('hr', '0003_add_verbose_name_20190213_1519'),
    ]

    operations = [
        migrations.RunPython(create_urechr_user),
    ]
Run Code Online (Sandbox Code Playgroud)

AttributeError: type object 'User' has no attribute 'normalize_username'

Dos*_*Dos 7

您应该使用create()而不是create_user(),因为 UserManager 在迁移中不起作用。确保以正确的方式生成密码。

from django.contrib.auth.hashers import make_password

def create_urechr_user(apps, schema_editor):
    # ...
    user = User.objects.create(
        username = "myName",
        password = make_password("test"),
        is_active = True,
        email = "",
    )
    # ...
Run Code Online (Sandbox Code Playgroud)