django.db.utils.ProgrammingError:关系“users_user”不存在
Posted
技术标签:
【中文标题】django.db.utils.ProgrammingError:关系“users_user”不存在【英文标题】:django.db.utils.ProgrammingError: relation "users_user" does not exist 【发布时间】:2018-05-11 06:06:24 【问题描述】:我正在尝试迁移我的应用程序,因此发生了此错误“”。 我尝试了很多方法,但没有运行。我正在使用多租户配置。请帮帮我。
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 -- 从 未来 导入 unicode_literals 从 django.utils.http 导入 urlquote 从 django.db 导入模型 从 django.contrib.auth.base_user 导入 AbstractBaseUser、BaseUserManager 从 django.contrib.auth.models 导入 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 -- 从 未来 导入 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
【问题讨论】:
你的项目结构是什么?您有名为 users 的应用吗? 是的,我有一个名为 users 的应用程序,并且在 models.py 中有一个名为 User 的模型。我正在使用来自 django user_auth_model 的抽象用户。 您是否同时找到了解决方案?遇到同样的问题。 同样的问题。 同样的问题 【参考方案1】:您是否设法解决了这个问题?如果没有,这对我有用:
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))
迁移命令:
-
python manage.py makemigrations 客户
python manage.py makemigrations 用户
python manage.py migrate_schemas --shared
【讨论】:
【参考方案2】:正如@mjoyshuvo 所说
'app.user'
应该同时在 TENANT_APPS 和 SHARED_APPS 上,因为共享应用程序中的某些应用程序尝试引用它,但它似乎不存在。 p>
【讨论】:
以上是关于django.db.utils.ProgrammingError:关系“users_user”不存在的主要内容,如果未能解决你的问题,请参考以下文章