django.db.utils.ProgrammingError:关系“users_user”不存在

时间:2017-11-27 21:54:47

标签: django multi-tenant

我正在尝试迁移我的应用,因此发生此错误“django.db.utils.ProgrammingError:relation”users_user“不存在”。 我尝试了很多方法而且没有运行。我正在使用多租户配置。请帮帮我。

    My manage.py migrate_schemas --list
    [standard:public] admin
    [standard:public]  [ ] 0001_initial
    [standard:public]  [ ] 0002_logentry_remove_auto_add
    [standard:public]  [ ] 0003_auto_20171127_1309
    [standard:public] auth
    [standard:public]  [X] 0001_initial
    [standard:public]  [X] 0002_alter_permission_name_max_length 
    [standard:public]  [X] 0003_alter_user_email_max_length
    [standard:public]  [X] 0004_alter_user_username_opts
    [standard:public]  [X] 0005_alter_user_last_login_null
    [standard:public]  [X] 0006_require_contenttypes_0002
    [standard:public]  [X] 0007_alter_validators_add_error_messages
    [standard:public] contenttypes
    [standard:public]  [X] 0001_initial
    [standard:public]  [X] 0002_remove_content_type_name
    [standard:public] foundation
    [standard:public]  (no migrations)
    [standard:public] sessions
    [standard:public]  [ ] 0001_initial
    [standard:public] sites
    [standard:public]  [X] 0001_initial
    [standard:public]  [X] 0002_alter_domain_unique
    [standard:public] tenants
    [standard:public]  (no migrations)
    [standard:public] users
    [standard:public]  [X] 0001_initial
    Traceback (most recent call last):
    File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
    File "C:\Python27\lib\site-packages\django\core\management\__init__.py", 
    line 350, in execute_from_command_line
    utility.execute()
    File "C:\Python27\lib\site-packages\django\core\management\__init__.py", 
    line 342, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
    File "C:\Python27\lib\site-packages\django\core\management\base.py", line 
    348, in run_from_argv
    self.execute(*args, **cmd_options)
    File "C:\Python27\lib\site-packages\django\core\management\base.py", line 
    399, in execute
    output = self.handle(*args, **options)
    File "C:\Python27\lib\site-
    packages\tenant_schemas\management\commands\migrate_schemas.py", line 53, 
    in handle
    executor.run_migrations(tenants=tenants)
    File "C:\Python27\lib\site-
    packages\tenant_schemas\migration_executors\base.py", line 57, in 
    run_migrations
    if public_schema_name in tenants:
    TypeError: argument of type 'TenantQueryset' is not iterable

settings.py         “””         ViaPortal_2项目的Django设置。

    Generated by 'django-admin startproject' using Django 1.9.

    For more information on this file, see
    https://docs.djangoproject.com/en/1.11/topics/settings/

    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/1.11/ref/settings/
    """


    import os

    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))


    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = '*3*_u^(l*1ayvv+k578+^32u8ble*^d&#n=91ou%th0&1bp60^'

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True

    ALLOWED_HOSTS = ['softvini.pythonanywhere.com',u'localhost' ]


    # Application definition

    SHARED_APPS = (
        'tenant_schemas',  # mandatory, should always be before any django app
        'tenants', # you must list the app where your tenant model resides in

        'django.contrib.contenttypes',

        # everything below here is optional
        'django.contrib.auth',
        'django.contrib.sessions',
       # 'django.contrib.sites',
        'django.contrib.messages',
        'django.contrib.admin',


    )

    TENANT_APPS = (
        'django.contrib.contenttypes',

        # your tenant-specific apps
        'users',
        'foundation',
        'notifications',

    )


    INSTALLED_APPS = [
        'tenant_schemas',

        'tenants',
        'django.contrib.contenttypes',
        'django.contrib.auth',
        'django.contrib.sessions',
        #'django.contrib.sites',
        'django.contrib.messages',
        'django.contrib.admin',

        'widget_tweaks',
        'foundation',
        'users',
        'notifications',
        'main',

    ]

    TENANT_MODEL = "tenants.Tenant" # app.Model
    AUTH_USER_MODEL = 'users.User'



    LOGIN_URL = 'auth/login/'



    DATABASE_ROUTERS = (
        'tenant_schemas.routers.TenantSyncRouter',
    )


    MIDDLEWARE_CLASSES = [
        'tenant_schemas.middleware.TenantMiddleware',
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]


    MIGRATION_MODULES = {       
        'sites': 'contrib.sites.migrations'         
    }

    ROOT_URLCONF = 'ViaPortal_2.urls'

    '''
    TEMPLATE_LOADERS = (
        'django.template.loaders.filesystem.Loader',
        'django.template.loaders.app_directories.Loader',
    )
    '''
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(PROJECT_PATH, 'templates'),],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]

    WSGI_APPLICATION = 'ViaPortal_2.wsgi.application'


    # Database
    # https://docs.djangoproject.com/en/1.11/ref/settings/#databases


    DATABASES = {

       'default': {
           'ENGINE': 'tenant_schemas.postgresql_backend', 
           'NAME': 'viaportal_py',
           'USER': 'postgres',
           'PASSWORD': 'my_pass',
           'HOST': 'localhost',
           'PORT': '5432',
        }         


    }



    # Password validation
    # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]


    # Internationalization
    # https://docs.djangoproject.com/en/1.11/topics/i18n/

    LANGUAGE_CODE = 'pt-br'

    TIME_ZONE = 'UTC'

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True


    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/1.11/howto/static-files/

    STATIC_URL = '/static/'
    STATIC_ROOT = os.path.join(PROJECT_PATH )
    MEDIA_ROOT = os.path.join(PROJECT_PATH,'media')
    MEDIA_URL = '/media/'

    DEFAULT_FILE_STORAGE = 'tenant_schemas.storage.TenantFileSystemStorage'

    STATICFILES_DIRS = (
        os.path.join(PROJECT_PATH, '/static/'),
        # '/var/www/static/',
    )





>

users.models.py         # - - 编码:utf-8 - -         来自 future 导入unicode_literals         来自django.utils.http import urlquote         来自django.db导入模型         来自django.contrib.auth.base_user导入AbstractBaseUser,BaseUserManager         来自django.contrib.auth.models import PermissionsMixin

    class UserManager(BaseUserManager):
        def create_user(self, *args, **kwargs):
            email = kwargs["email"]
            email = self.normalize_email(email)
            password = kwargs["password"]
            kwargs.pop("password")

            if not email:
                raise ValueError(_('É obrigatório informar um e-mail válido'))

            user = self.model(**kwargs)
            user.set_password(password)
            user.save(using=self._db)
            return user

        def get_short_name(self):
            "Returns the short name for the user."
            return self.first_name

        def create_superuser(self, *args, **kwargs):
            user = self.create_user(**kwargs)
            user.is_superuser = True
            user.is_staff = True
            user.save(using=self._db)
            return user
        @property
        def is_superuser(self):
            return self.is_admin

        @property
        def is_staff(self):
            return self.is_admin

        def has_perm(self, perm, obj=None):
            return self.is_admin

        def has_module_perms(self, app_label):
            return self.is_admin

    class User(PermissionsMixin, AbstractBaseUser):
        email = models.EmailField(
            verbose_name = ('Endereco de e-mail'),
            unique=True,
        )
        first_name = models.CharField(
            verbose_name = ('Nome'),
            max_length=50,
            blank=False,
            help_text= ('Informe seu nome'),
        )
        last_name = models.CharField(
            verbose_name= ('Sobrenome'),
            max_length=50,
            blank=False,
            help_text= ('Informe seu sobre nome'),
        )

        is_active = models.BooleanField(default=True)
        is_admin = models.BooleanField(default=False)
        is_staff = models.BooleanField(default=False)

        empresa   = models.ForeignKey('foundation.Empresa', blank=True, null=True)
        estabelecimento = models.ForeignKey('foundation.Estabelecimento', blank=True, null=True)

        def get_absolute_url(self):
            return "/users/%s/" % urlquote(self.pk)

        def get_full_name(self):
            """
            Returns the first_name plus the last_name, with a space in between.
            """
            full_name = '%s %s' % (self.first_name, self.last_name)
            return full_name.strip()

        def get_short_name(self):
            "Returns the short name for the user."
            return self.first_name

        USERNAME_FIELD = 'email'

        objects = UserManager()

    class Profile(models.Model):
        user = models.OneToOneField(User, related_name='profile')
        image_profile = models.ImageField(upload_to = 'static/users/', default = 'static/users/no-img.jpg') 
        Gender_Choices = (
            ('F', 'Feminino'),
            ('M', 'Masculino'),
            ('O', 'Outro'),
        )
        gender = models.CharField(max_length=1, choices= Gender_Choices)
        description   = models.TextField(max_length=300,blank=True, null=True)

foundation.models.py         # - - 编码:utf-8 - -         来自 future 导入unicode_literals         来自django.db导入模型         来自django.conf导入设置

    from datetime import datetime
    from django.utils import timezone
    # Create your models here.

    # Create your models here.



    class Empresa(models.Model):
        cod_empresa = models.CharField(max_length=5, unique=True)
        nome                = models.CharField(max_length=100)
        created_by = models.ForeignKey( settings.AUTH_USER_MODEL , related_name="creation_user_empresa",blank=True, null=True)
        created_date = models.DateField(default=timezone.now,blank=True)
        class Meta:
            verbose_name = (u'Empresa')
            verbose_name_plural = (u'Empresas')

        def __str__(self):
            return self.cod_empresa + " - " + self.nome   

        def __unicode__(self):
            return self.cod_empresa + " - " + self.nome

    class Estabelecimento(models.Model):
        cod_estabelecimento = models.CharField(max_length=5, unique=True)
        nome                = models.CharField(max_length=100)
        razao_social        = models.CharField(max_length=1000, blank=True)
        empresa             = models.ForeignKey(Empresa)
        logo_estab          = models.ImageField(upload_to = 'estabelecimentos/', default = 'estabelecimentos/no-estabelec.png') 
        created_by          = models.ForeignKey( settings.AUTH_USER_MODEL  , related_name="creation_user_estabelecimento",blank=True, null=True)
        created_date        = models.DateField(default=timezone.now,blank=True)
        class Meta:
            verbose_name = (u'Estabelecimento')
            verbose_name_plural = (u'Estabelecimentos')

        def __str__(self):
            return self.cod_estabelecimento + " - " + self.nome

        def __unicode__(self):
            return self.cod_estabelecimento + " - " + self.nome 


    class CentroCusto(models.Model):
        cod_centrocusto = models.CharField(max_length=20, unique=True)
        nome = models.CharField(max_length=100)
        estabelecimento = models.ForeignKey(Estabelecimento) 
        created_by          = models.ForeignKey( settings.AUTH_USER_MODEL  , related_name="creation_user_centrocusto",blank=True, null=True)
        created_date        = models.DateField(default=timezone.now,blank=True)

        class Meta:
            verbose_name = (u'Centro de Custo')
            verbose_name_plural = (u'Centros de Custos')

        def __str__(self):
            return self.cod_centrocusto + " - " + self.nome 

        def __unicode__(self):
            return self.cod_centrocusto + " - " + self.nome

    class Departamento(models.Model):
        nome = models.CharField(max_length=100)
        estabelecimento = models.ForeignKey(Estabelecimento)
        centroCusto = models.ForeignKey(CentroCusto)
        created_by          = models.ForeignKey( settings.AUTH_USER_MODEL  , related_name="creation_user_departamento" ,blank=True, null=True)
        created_date        = models.DateField(default=timezone.now,blank=True)

        class Meta:
            verbose_name = (u'Centro de Custo')
            verbose_name_plural = (u'Centros de Custos')

        def __str__(self):
            return self.nome 
        def __unicode__(self):
            return self.nome

2 个答案:

答案 0 :(得分:2)

您设法解决了这个问题吗?如果没有,这对我有用:

SHARED_APPS = (
'tenant_schemas',  # mandatory
'apps.user',
'apps.customer',  # must list the app where tenant model resides in
'django.contrib.contenttypes',
# everything below here is optional
'rest_framework',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'django.contrib.staticfiles',
'django_extensions',
)
TENANT_APPS = (
'apps.user',
'apps.home',
'django.contrib.contenttypes',
# tenant-specific apps
)
INSTALLED_APPS = list(set(SHARED_APPS + TENANT_APPS))

迁移命令:

  1. python manage.py makemigrations客户
  2. python manage.py makemigrations用户
  3. python manage.py migrate_schemas --shared

答案 1 :(得分:1)

正如@mjoyshuvo 所说

'app.user'

应该在 TENANT_APPSSHARED_APPS 上,因为共享应用程序中的某些应用程序尝试引用它,但它似乎不存在。 >