Data migration causes error AttributeError: type object 'User' has no attribute 'normalize_username'?

Viewed 1469

I'm trying to create a data migration to add a user to the database. However, I get an attribute error when I try to do so.

I've ran ipdb to troubleshoot the problem, I've tried commenting out fields of the user object to see if one of those was causing the error, and I've tried adding "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),
    ]

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

1 Answers

You should use create() instead of create_user(), as the UserManager doesn't work inside migrations. Make sure you are generating the password in the correct way.

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 = "",
    )
    # ...
Related