Custom user models in Django: `no such table: auth

2019-09-06 05:37发布

问题:

According to the answer to my previous question, I edited the django-registration module with the following modifications:

in myapp/models.py:

from django.contrib.auth.models import UserManager
from django.contrib.auth.models import AbstractUser

class AccountManager(UserManager):
    def create_user(self, email, password=None, **kwargs):
        if not email:
            raise ValueError('Users must have a valid email address.')
        if not kwargs.get('username'):
            raise ValueError('Users must have a valid username.')

        account = self.model(
            email=self.normalize_email(email), 
            username=kwargs.get('username'), 
            #year_of_birth = kwargs.get('year_of_birth'),
            #MODEL = kwargs.get('MODEL_NAME'),
        )
        account.set_password(password)
        account.save()

        return account

    def create_superuser(self, email, password, **kwargs):
        account = self.create_user(email, password, **kwargs)
        account.is_staff = True
        account.is_superuser = True
        account.save()

        return account

class Account(AbstractUser):
    #email = models.EmailField(unique=True)
    points = models.FloatField(default = 100.0)
    #ADD YOUR MODELS HERE

    objects = AccountManager()

    def __str__(self):
        return "Account: "+self.username

and in myproject/settings.py:

AUTH_USER_MODEL = 'myapp.Account'

now the rest of the application works (i.e. refers to Account which also has base fields from the User model). However, the django-registration module itself is not working now. When I send a new registration form (with username, email and password), I get the error:

OperationalError at /accounts/register/
no such table: auth_user

I tried a lot of combinations of makemigrations and migrate (also with --fake and --fake-initial arguments) but (I guess) the auth table is not initializing with the new settings.

How can I fix this so I can keep registering with the new Account model while not harming the default auth module's User model?

Thanks for any help,

Edit

When I tried to see the users in shell, I got this error which makes things a little bit clearer:

>>> from django.contrib.auth.models import User
>>> users = User.objects.all()
AttributeError: Manager isn't available; User has been swapped for 'myapp.Account'

So it looks like my new model Account has overwritten the default User model. If so, why is the registration module looking for the auth_user table? Doesn't the modification in settings.py aim to fix this?

回答1:

You can't swap user model for any app that refers to it, if migrations for that app have been applied. Try to re-create your database by creating new one, reapplying migrations on it and then moving data from old database