4

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'

6
  • What code calls normalize_username? It's not that migration. Commented Jun 26, 2019 at 22:47
  • Do you have a custom user model? Would you mind sharing the model code?
    – chamoda
    Commented Jun 27, 2019 at 2:51
  • @chamoda I'm not using a custom user model. I'm using the one that Django provides.
    – user11517082
    Commented Jun 27, 2019 at 12:00
  • @markwalker_ I searched through the project and normalize_username is not called anywhere and does not appear at all in the project which is one of the main reasons that I'm confused by this error.
    – user11517082
    Commented Jun 27, 2019 at 12:04
  • @Rachel what version of django are you using? Commented Jun 27, 2019 at 12:11

1 Answer 1

8

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.