0

After running a migration I get the following error:

LookupError: Model 'users.UserProfile' not registered.

I am trying to create a customer User for Django-cms. It just does not want to do it.

Full Traceback:

Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\user\Envs\p37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Users\user\Envs\p37\lib\site-packages\django\core\management\__init__.py", line 357, in execute
django.setup()
File "C:\Users\user\Envs\p37\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\user\Envs\p37\lib\site-packages\django\apps\registry.py", line 112, in populate
app_config.import_models()
File "C:\Users\user\Envs\p37\lib\site-packages\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\user\Envs\p37\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\user\Envs\p37\lib\site-packages\djangocms_text_ckeditor\models.py", line 10, in <module>
from cms.models import CMSPlugin
File "C:\Users\user\Envs\p37\lib\site-packages\cms\models\__init__.py", line 4, in <module>
from .permissionmodels import *  # nopyflakes
File "C:\Users\user\Envs\p37\lib\site-packages\cms\models\permissionmodels.py", line 21, in <module>
User = apps.get_registered_model(user_app_name, user_model_name)
File "C:\Users\user\Envs\p37\lib\site-packages\django\apps\registry.py", line 270, in get_registered_model
"Model '%s.%s' not registered." % (app_label, model_name))
LookupError: Model 'users.UserProfile' not registered.

Models.py file:

from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.utils.translation import gettext_lazy as _
from django.utils import timezone
from .managers import UserProfileManager


class UserPlans(models.Model):
    plan = models.CharField(max_length=255)

    def get_plan_choices_data(self):
        return UserPlans.objects.values_list('id', 'plan')

    class Meta:
        verbose_name = 'Plan'


class EnglishInterest(models.Model):
    english_interest = models.CharField(max_length=255)

    def get_english_interest_data(self):
        return EnglishInterest.objects.values_list('id', 'english_interest')


class UserProfile(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(default=timezone.now)
    english_interest = models.CharField(max_length=255)
    plan_choice = models.CharField(max_length=255)
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    age = models.IntegerField()
    location = models.CharField(max_length=255)
    english_interest = models.ForeignKey(
    EnglishInterest, on_delete=models.CASCADE, default='general speaking')
    plan = models.ForeignKey(
    UserPlans, on_delete=models.CASCADE, default='monthly')
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['english_interest', 'plan_choice',
                   'first_name', 'last_name', 'age', 'location']

    objects = UserProfileManager()


    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        # "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        # "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        # "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin

Managers.py

from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import ugettext_lazy as _


class UserProfileManager(BaseUserManager):
    """
    Custom user model manager where email is the unique identifiers
    for authentication instead of usernames.
    """

    def create_user(self, email, password, **extra_fields):
        """
        Create and save a User with the given email and password.
        """
        if not email:
            raise ValueError(_('The Email must be set'))
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password, **extra_fields):
        """
        Create and save a SuperUser with the given email and password.
        """
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError(_('Superuser must have is_staff=True.'))
        if extra_fields.get('is_superuser') is not True:
            raise ValueError(_('Superuser must have is_superuser=True.'))
        return self.create_user(email, password, **extra_fields)

admin.py file

from django.contrib import admin
from .models import EnglishInterest, UserPlans, UserProfile
from django import forms
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField


class UserProfileForm(forms.ModelForm):

    ENGLISH_INTEREST = EnglishInterest().get_english_interest_data()
    PLAN_CHOICES = UserPlans().get_plan_choices_data()

    email = forms.EmailField(max_length=255, required=True, widget=forms.TextInput(attrs={
                         'type': 'email', 'class': 'form-control', 'name': 'email', 'placeholder': 'Email', 'data-validetta': 'required,email'}))

    password1 = forms.CharField(max_length=255, required=True, widget=forms.TextInput(
    attrs={'type': 'password', 'class': 'form-control', 'name': 'password1', 'placeholder': 'Password', 'data-validetta': 'required,minLength[4],maxLength[20]'}))
    password2 = forms.CharField(max_length=255, required=True, widget=forms.TextInput(
    attrs={'type': 'password', 'class': 'form-control', 'name': 'password1', 'placeholder': 'Confirm Password', 'data-validetta': 'required,minLength[4],maxLength[20],equalTo[password1]'}))
    nextButton = forms.CharField(widget=forms.TextInput(
    attrs={'type': 'button', 'name': 'next', 'class': 'next action-button', 'value': 'Next'}))

    english_interest = forms.MultipleChoiceField(choices=ENGLISH_INTEREST, widget=forms.CheckboxSelectMultiple(
    attrs={'name': 'english_interest', 'data-validetta': 'minChecked[1],maxChecked[4]'}))
    plan_choices = forms.ChoiceField(choices=PLAN_CHOICES, widget=forms.RadioSelect(
    attrs={'name': 'plan', 'data-validetta': 'minRadio[1]'}))
previousButton = forms.CharField(widget=forms.TextInput(
    attrs={'type': 'button', 'name': 'previous', 'class': 'previous action-button', 'value': 'Previous'}))
nextButton2 = forms.CharField(widget=forms.TextInput(
    attrs={'type': 'button', 'name': 'next2', 'class': 'next action-button', 'value': 'Next'}))

    first_name = forms.CharField(max_length=255, required=True, widget=forms.TextInput(
    attrs={'type': 'text', 'name': 'first_name', 'placeholder': 'First Name', 'data-validetta': 'required'}))
    last_name = forms.CharField(max_length=255, required=True, widget=forms.TextInput(
    attrs={'type': 'text', 'name': 'last_name', 'placeholder': 'Last Name', 'data-validetta': 'required'}))
    age = forms.IntegerField(min_value=1, max_value=2, required=True, widget=forms.TextInput(attrs={
                         'type': 'number', 'name': 'age', 'placeholder': 'Age', 'data-validetta': 'required,minLength[1],maxLength[2],number'}))
    location = forms.CharField(max_length=255, required=True, widget=forms.TextInput(
    attrs={'type': 'text', 'name': 'location', 'placeholder': 'Location', 'data-validetta': 'required'}))
    previousButton2 = forms.CharField(widget=forms.TextInput(
    attrs={'type': 'button', 'name': 'previous2', 'class': 'previous action-button', 'value': 'Previous'}))
submitButton = forms.CharField(widget=forms.TextInput(
    attrs={'type': 'submit', 'name': 'submit', 'class': 'submit action-button', 'value': 'Submit'}))

    class Meta:
        model = UserProfile
        fields = ('email', 'password1', 'password2', 'english_interest',
              'plan_choices', 'first_name', 'last_name', 'age', 'location')

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class UserChangeForm(forms.ModelForm):
    """A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
    """
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = UserProfile
        fields = ('email', 'password1', 'password2', 'english_interest',
              'plan_choices', 'first_name', 'last_name', 'age', 'location', 'is_active', 'is_admin')

    def clean_password(self):
        # Regardless of what the user provides, return the initial value.
        # This is done here, rather than on the field, because the
        # field does not have access to the initial value
        return self.initial["password"]


class UserAdmin(BaseUserAdmin):
    # The forms to add and change user instances
    form = UserChangeForm
    add_form = UserProfileForm

    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ('email', 'is_admin')
    list_filter = ('is_admin',)
fieldsets = (
    (None, {'fields': ('email', 'password')}),
    ('Personal info', {'fields': ('age',)}),
    ('Permissions', {'fields': ('is_admin',)}),
)
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
    (None, {
        'classes': ('wide',),
        'fields': ('email', 'age', 'password1', 'password2')}
     ),
)
    search_fields = ('email',)
    ordering = ('email',)
    filter_horizontal = ()


admin.site.register(EnglishInterest)
admin.site.register(UserPlans)

# Now register the new UserAdmin...
admin.site.register(UserProfile, UserAdmin)
# ... and, since we're not using Django's built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)

And yes, I do have in my settings.py: AUTH_USER_MODEL = 'users.UserProfile'

and in Installed apps my user app does come before cms:

INSTALLED_APPS[
    ...    
    'users',
    'cms',
     ...
]
Lawrence DeSouza
  • 984
  • 5
  • 16
  • 34
  • 2
    Is 'users' also listed before 'django.contrib.auth' and 'django.contrib.admin'? It should be the top-most app in your `INSTALLED_APPS`. – dirkgroten Aug 05 '19 at 10:27
  • Unreal, I can't believe that worked. Now I'm getting a different error. django.core.exceptions.FieldError: Unknown field(s) (is_admin, plan_choices, password2, password1) specified for UserProfile – Lawrence DeSouza Aug 05 '19 at 10:40
  • The `fields` variable should only list fields that you want to take from your model `UserProfile`, not any custom field you're adding to your form. `is_admin`, `plan_choices`, `password1` and `password2` don't exist on `UserProfile` model. – dirkgroten Aug 05 '19 at 10:44
  • Side note: `def has_perm(): return True` is not a good idea. You're allowing everyone to make changes to any model like that. – dirkgroten Aug 05 '19 at 10:47
  • Just an observation, but your UserProfile class has the superclasses listed in reverse order. You probably want the Mixin class to come first, then the abstract class. Like this: `class UserProfile(PermissionsMixin, AbstractBaseUser)` For more info see [here](https://stackoverflow.com/questions/10018757/how-does-the-order-of-mixins-affect-the-derived-class) – matias elgart Aug 05 '19 at 11:16
  • I think I've got the fields sorted out now, but there is another error: django.db.utils.IntegrityError: (1364, "Field 'name' doesn't have a default value") seems to be originating from the query: b"INSERT INTO `django_content_type` (`app_label`, `model`) VALUES ('admin', 'logentry')" – Lawrence DeSouza Aug 05 '19 at 11:40

0 Answers0