Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AUTH_USER_MODEL refers to model .. that has not been installed and created AbstractUser models not able to login

AUTH_USER_MODEL error solved in EDIT3. Passwords still will not save on user creation via form.

I'm using Django 1.5 playing around with the new user override/extension features, and I am not able to register new users via my registration form - only via the Admin. When registering via the registration form, I get the following error:

Manager isn't available; User has been swapped for 'poker.PokerUser'

models.py:

class PokerUser(AbstractUser):     poker_relate = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)     token = models.EmailField()     USER_CHOICES = (         ('1', 'Staker'),         ('2', 'Horse')     )     user_type = models.CharField(choices=USER_CHOICES, max_length=10)     username1 = models.CharField(null=True, blank=True, max_length=40)     username2 = models.CharField(null=True, blank=True, max_length=40)     username3 = models.CharField(null=True, blank=True, max_length=40)     username4 = models.CharField(null=True, blank=True, max_length=40)     username5 = models.CharField(null=True, blank=True, max_length=40) 

PokerUserForm model:

class PokerUserForm(UserCreationForm):     class Meta:         model = PokerUser         fields = ('username','password1','password2','email','user_type','token','username1','username2','username3','username4','username5',) 

I've attempted to change the model in the PokerUserForm model to use get_user_model() instead of explicitly defining the model by setting model = get_user_model() instead of model = PokerUser but then I receive the following error:

django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'poker.PokerUser' that has not been installed 

My AUTH_USER_MODEL is setup in my settings.py like so:

AUTH_USER_MODEL = 'poker.PokerUser'

On we go - my Registration view in views.py:

def UserRegistration(request):     player = PokerUser()      if request.method == 'POST':         form = PokerUserForm(request.POST, instance=player)         if form.is_valid():             player.email_address = form.cleaned_data['email']             player.user_type = form.cleaned_data['user_type']             # if player is staker, token is their own email. otherwise their token is their staker's email and             # their relation is their staker             if player.user_type == '1' or player.user_type == 'staker':                 player.token = player.email_address             else:                 player.token = form.cleaned_data['token']                 staker = PokerUser.objects.get(email=player.token)                 player.poker_relate = staker             player.save()             return HttpResponseRedirect('/')     else:         form = PokerUserForm()     initialData = {'form': form}     csrfContext = RequestContext(request, initialData)     return render_to_response('registration/register.html', csrfContext) 

EDIT1:

According to the docs, the UserCreationForm must be recreated for use with custom user classes.

I overrode the entire UserCreationForm as follows:

class UserCreationForm(forms.ModelForm):     """     A form that creates a user, with no privileges, from the given username and     password.     """     error_messages = {         'duplicate_username': _("A user with that username already exists."),         'password_mismatch': _("The two password fields didn't match."),         }     username = forms.RegexField(label=_("Username"), max_length=30,         regex=r'^[\w.@+-]+$',         help_text=_("Required. 30 characters or fewer. Letters, digits and "                     "@/./+/-/_ only."),         error_messages={             'invalid': _("This value may contain only letters, numbers and "                          "@/./+/-/_ characters.")})     password1 = forms.CharField(label=_("Password"),         widget=forms.PasswordInput)     password2 = forms.CharField(label=_("Password confirmation"),         widget=forms.PasswordInput,         help_text=_("Enter the same password as above, for verification."))      class Meta:         model = PokerUser         fields = ('username','password1','password2','email','user_type','token','username1','username2','username3','username4','username5',)      def clean_username(self):         # Since User.username is unique, this check is redundant,         # but it sets a nicer error message than the ORM. See #13147.         username = self.cleaned_data["username"]         try:             PokerUser.objects.get(username=username)         except PokerUser.DoesNotExist:             return username         raise forms.ValidationError(self.error_messages['duplicate_username'])      def clean_password2(self):         password1 = self.cleaned_data.get("password1")         password2 = self.cleaned_data.get("password2")         if password1 and password2 and password1 != password2:             raise forms.ValidationError(                 self.error_messages['password_mismatch'])         return password2      def save(self, commit=True):         user = super(UserCreationForm, self).save(commit=False)         user.set_password(self.cleaned_data["password1"])         if commit:             user.save()         return user 

And this was able to resolve this error:

The Manager isn't available; User has been swapped for 'poker.PokerUser'

Now, the users get created but are not able to log in. When I check the users in the admin, all of the information seems to be correct except for the password. Adding a password manually in the admin does not seem to work correctly. Still, adding users via the admin work correctly.

EDIT 2:

I'm still unable to login as any of my AbstractUser models created via the registration form. I have completely overridden the UserCreationForm as outlined above, and am unable to implement get_user_model() with this error:

AUTH_USER_MODEL refers to model 'poker.PokerUser' that has not been installed

The Django code for get_user_model() is:

 def get_user_model():     "Return the User model that is active in this project"     from django.conf import settings     from django.db.models import get_model      try:         app_label, model_name = settings.AUTH_USER_MODEL.split('.')     except ValueError:         raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form 'app_label.model_name'")     user_model = get_model(app_label, model_name)     if user_model is None:         raise ImproperlyConfigured("AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL)     return user_model 

Since I have AUTH_USER_MODEL = 'poker.PokerUser' setup in my settings.py, this should work. I've verified this through the Django console:

>>> from django.contrib.auth import get_user_model >>> settings.AUTH_USER_MODEL Out[14]: 'poker.PokerUser' >>> from django.db.models import get_model >>> app_label, model_name = settings.AUTH_USER_MODEL.split('.') >>> user_model = get_model(app_label, model_name) >>> user_model Out[18]: poker.models.PokerUser 

However the implementation still does not work correctly.

If you've read this far, thanks!

EDIT3:

AUTH_USER_MODEL refers to model 'poker.PokerUser' that has not been installed has been fixed. I accidentally had the UserCreationForm that I recreated in poker.models instead of registration.forms, so when I ran get_user_model() that was assigned to poker.PokerUser, it couldn't resolve since it was already in that location.

Now the only issue left is that when creating new users, their passwords will not save. I've narrowed it down to a single method in the UserCreationForm by placing print statements here:

def clean_password2(self):     password1 = self.cleaned_data.get("password1")     print password1     password2 = self.cleaned_data.get("password2")     print password2     if password1 and password2 and password1 != password2:         raise forms.ValidationError(             self.error_messages['password_mismatch'])     print password2     return password2  def save(self, commit=True):     user = super(UserCreationForm, self).save(commit=False)     user.set_password(self.cleaned_data["password1"])     print self.cleaned_data["password1"]     if commit:         user.save()     return user 

The print password1 and print password1 statements in clean_password2 display the plain text password, but print self.cleaned_data["password1"] in the save method is blank. Why is my form data not being passed to the save method?

TL;DR AbstractUser model creation is working in both Admin and via registration form, but only the users created via Admin are able to login. The users created via the registration form are unable to log in and seem to be saved without a password - all other information is saved correctly.

like image 686
Dan Hoerst Avatar asked Feb 05 '13 03:02

Dan Hoerst


People also ask

What is Auth_user_model in Django?

Django allows you to override the default user model by providing a value for the AUTH_USER_MODEL setting that references a custom model. Method 2 – AUTH_USER_MODEL : AUTH_USER_MODEL is the recommended approach when referring to a user model in a models.py file.

What is PermissionsMixin in django?

The PermissionsMixin is a mixin for models. The PermissionsMixin [Django-doc] is a mixin for Django models. If you add the mixin to one of your models, it will add fields that are specific for objects that have permissions, like is_superuser , groups , and user_permissions .


1 Answers

I've run into this a few times. It's always been an import issue. Suppose we have core/models.py that implements a custom user and imports a symbol from another file (say Else):

from Something import Else  class CustomUser(AbstractBaseUser):     pass 

And then we have another file that uses CustomUser and also defines Else. Let's call this something/models.py:

from core.models import CustomUser  class Else(models.Model):     pass  class AnotherClass(models.model):     user = models.ForeignKey(CustomUser) 

When core/models.py goes to import Else, it evaluates something/models.py and runs into the AnotherClass definition. AnotherClass uses CustomUser, but CustomUser hasn't been installed yet because we're in the process of creating it. So, it throws this error.

I've solved this problem by keeping my core/models.py standalone. It doesn't import much from my other apps.

like image 114
Rob Jones Avatar answered Sep 18 '22 11:09

Rob Jones