分享
三行代码  ›  专栏  ›  技术社区  ›  brad

createsuperuser仅在postgresql上失败

  •  0
  • brad  · 技术社区  · 1 周前

    我可以使用sqlite3使代码和数据库在本地正常工作。但是当我尝试迁移到postgresql平台时,当我尝试创建超级用户时会出现错误,而不是迁移或进行迁移。

    (trader) bubba@tuna:~/www/src/trader $ ./manage.py makemigrations                         
    No changes detected
    (trader) bubba@tuna:~/www/src/trader $ ./manage.py migrate        
    Operations to perform:
      Apply all migrations: accounts, admin, auth, contenttypes, sessions
    Running migrations:
      No migrations to apply.
    (trader) bubba@tuna:~/www/src/trader $ ./manage.py createsuperuser
    Username (leave blank to use 'bubba'): 
    Email address: bubba@trader.com
    Password: 
    Password (again): 
    Traceback (most recent call last):
      File "./manage.py", line 21, in <module>
        main()
      File "./manage.py", line 17, in main
        execute_from_command_line(sys.argv)
      File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
        utility.execute()
      File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
        self.fetch_command(subcommand).run_from_argv(self.argv)
      File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv
        self.execute(*args, **cmd_options)
      File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute
        return super().execute(*args, **options)
      File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute
        output = self.handle(*args, **options)
      File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle
        self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
      File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/contrib/auth/models.py", line 158, in create_superuser
        return self._create_user(username, email, password, **extra_fields)
      File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/contrib/auth/models.py", line 141, in _create_user
        user.save(using=self._db)
      File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 66, in save
        super().save(*args, **kwargs)
      File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/db/models/base.py", line 746, in save
        force_update=force_update, update_fields=update_fields)
      File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/db/models/base.py", line 795, in save_base
        update_fields=update_fields, raw=raw, using=using,
      File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in send
        for receiver in self._live_receivers(sender)
      File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp>
        for receiver in self._live_receivers(sender)
      File "/home/bubba/www/src/trader/accounts/signals.py", line 10, in customer_profile
        group = Group.objects.get(name='customer')
      File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
        return getattr(self.get_queryset(), name)(*args, **kwargs)
      File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/db/models/query.py", line 417, in get
        self.model._meta.object_name
    django.contrib.auth.models.DoesNotExist: Group matching query does not exist.
    

    $ cat trader/settings.py        
    """
    Django settings for trader project.
    
    Generated by 'django-admin startproject' using Django 3.0.6.
    
    For more information on this file, see
    https://docs.djangoproject.com/en/3.0/topics/settings/
    
    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/3.0/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__)))
    
    
    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
    
    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = 'boo'
    
    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True
    
    ALLOWED_HOSTS = ['127.0.0.1', '192.168.42.14']
    ALLOWED_CIDR_NETS = ['192.168.42.0/24']
    
    # Application definition
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'accounts.apps.AccountsConfig',
        'django_filters',
    ]
    
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]
    
    ROOT_URLCONF = 'trader.urls'
    
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            '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 = 'trader.wsgi.application'
    
    
    # Database
    # https://docs.djangoproject.com/en/3.0/ref/settings/#databases
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'expungee',
            'USER':'boo',
            'PASSWORD':'boo',
            'HOST':'192.168.42.13',
            'PORT':'5432',
        }
    }
    
    #DATABASES = {
    #    'default': {
    #        'ENGINE': 'django.db.backends.sqlite3',
    #        'NAME': os.path.join(BASE_DIR, '/home/bubba/www/src/trader/db.sqlite3'),
    #    }
    #}
    
    # Password validation
    # https://docs.djangoproject.com/en/3.0/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/3.0/topics/i18n/
    
    LANGUAGE_CODE = 'en-us'
    
    TIME_ZONE = 'UTC'
    
    USE_I18N = True
    
    USE_L10N = True
    
    USE_TZ = True
    
    
    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/3.0/howto/static-files/
    
    STATIC_URL = '/static/'
    
    MEDIA_URL = '/images/'
    
    STATIC_ROOT = os.path.join(BASE_DIR, "static/")
    
    STATICFILES_DIRS = [
            os.path.join(BASE_DIR, '/static')
    ]
    
    MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')
    

    我试过了

    django.db.backends.postgresql
    

    exchangedb=# \du
                                         List of roles
       Role name   |                         Attributes                         | Member of 
    ---------------+------------------------------------------------------------+-----------
     administrator | Superuser, Create role, Create DB                          | {}
     expungee      | Superuser, Create role, Create DB                          | {}
     expungeedb    |                                                            | {}
     postgres      | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
    

    我如何迁移到博士后?

    更新时间:

    $ cat accounts/signals.py 
    from django.db.models.signals import post_save
    from django.contrib.auth.models import User
    from django.contrib.auth.models import Group
    
    
    from .models import Customer
    
    def customer_profile(sender, instance, created, **kwargs):
            if created:
                    group = Group.objects.get(name='customer')
                    instance.groups.add(group)
                    Customer.objects.create(
                            user=instance,
                            name=instance.username,
                            )
                    print('Profile created!')
    
    post_save.connect(customer_profile, sender=User)
    
    1 回复  |  直到 1 周前
        1
  •  0
  •   bmons    1 周前

    group, created = Group.objects.get_or_create(name='customer')