Error trying to use a Custom User Model. Attributeerror: Manager isn’t available; 'auth.User' has been swapped for

Asked

Viewed 50 times

0

Hello.

Trying to create and use Custom Usermodel when running makemigrations or even running the server gets the error:

AttributeError: Manager isn't available; 'auth.User' has been swapped for 'autenticacao.UsuarioCustom'

Follows excerpt from my codes: py Settings., Forms.py and the model user_custom.py

Settings:

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'apps.autenticacao',
]

# Estamos definindo para o Django o Modelo padrão para a autentição, removendo o default que é o User da app Auth
AUTH_USER_MODEL = 'autenticacao.UsuarioCustom'

Models:

from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.db import models


class UsuarioCustomManager(BaseUserManager):
    """
    Classe criada para realizar a Administração do Model Usuário já que não usaremos o ambiente ADMIN padrão do Django
    """

    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """
        Função Privada para criar nossos usuários do sistema
        """

        if not email:
            raise ValueError('O e-mail é obrigatório')

        email = self.normalize_email(email)
        user = self.model(email=email, username=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)

        return user

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', False)

        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_istaff', True)

        return self._create_user(email, password, **extra_fields)


class UsuarioCustom(AbstractUser):

    class Meta:
        verbose_name = 'Usuário'
        verbose_name_plural = 'Usuários'
        abstract = False
        swappable = 'UsuarioCustom'

    email = models.EmailField(verbose_name='E-mail', unique=True)
    fone = models.CharField(verbose_name='Telefone', max_length=15)
    is_staff = models.BooleanField(verbose_name='Membro da equipe', default=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name', 'fone']

    def __str__(self):
        return self.email

    objects = UsuarioCustomManager()

Forms:

from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm, UserChangeForm


class UsuarioCustomCreateForm(UserCreationForm):

    class Meta:
        model = get_user_model()
        fields = ('first_name', 'last_name', 'fone')
        labels = {'username': 'Username/E-mail'}

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data['password1'])
        user.email = self.cleaned_data['username']

        if commit:
            user.save()
        return user

    def clean_username(self):
        username = self.cleaned_data["email"]
        try:
            get_user_model().objects.get(username=username)
        except get_user_model().DoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages['duplicate_username'])


class UsuarioCustomChangeForm(UserChangeForm):

    class Meta:
        model = get_user_model()
        fields = ('first_name', 'last_name', 'fone')
  • Packages installed in the project:
pip freeze
asgiref==3.2.5
coverage==5.0.4
cx-Oracle==6.4.1
Django==3.0.4
django-auth-ldap==2.1.1
djangorestframework==3.11.0
model-mommy==2.0.0
pkg-resources==0.0.0
pyasn1==0.4.8
pyasn1-modules==0.2.8
python-ldap==3.2.0
pytz==2019.3
sqlparse==0.3.1

I’ve researched and tried several solutions but I can’t get out of this mistake!

  • Your code has no error, at least not the way it is here, make a test: don’t install anything, just Django, start a project, create any app and paste the code of your model of your question in the app’s models file. Run the app and log in to admin. Have you started the system already with the custom user? If that’s not the case, try to change the user with the system already started is a source of problems, the documentation itself says this

  • 1

    @Sidon, thanks for the tips, went out isolating the parts of the project and found that the error was presenting because within the API area that I developed with rest_framework had a query using the user of contrib.auth, when adjusting for get_user_model() the problem ceased to exist. Thank you.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.