【问题标题】:How to create superuser in django through gcp?如何通过 gcp 在 django 中创建超级用户?
【发布时间】:2021-03-28 16:57:34
【问题描述】:

我最近将我的 django 项目部署到 gcp。部署进展顺利,我也可以访问该网址。我唯一不能做的就是登录管理面板。如何在 gcp 中运行 manage.py 命令,以便迁移和创建超级用户?

这就是我的 settings.py 文件的样子

"""
Django settings for portfolio_backend project.

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

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
from decouple import config
# import django_heroku
from dj_database_url import parse as dburl

# 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/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')

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

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'ckeditor',
    'corsheaders',
    'contact',
    'about',
    'work',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
    "http://localhost:3001",
    "https://portfolio-django-backend.herokuapp.com",
    "https://kiran-portfolio.herokuapp.com",
    "http://www.kirannambiar.in",
    "https://www.kirannambiar.in",
]

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ]
}

ROOT_URLCONF = 'portfolio_backend.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'portfolio/templates'), ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.media',
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'portfolio_backend.wsgi.application'


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

# default_dburl = 'sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3')


# DATABASES = {
#     'default': config('DATABASE_URL', default=default_dburl, cast=dburl),
# }

# if os.getenv('GAE_APPLICATION', None):
if os.getenv('SETTINGS_MODE') == 'prod':
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': "db-name",
            'USER': "username",
            'PASSWORD': "password",
            'HOST': "/cloudsql/kiran-nambiar:asia-south1:portfolio-db",
            '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 = 'en-us'

TIME_ZONE = 'Asia/Kolkata'

USE_I18N = True

USE_L10N = True

USE_TZ = True



# PROJECT_ROOT   =   os.path.join(os.path.abspath(__file__))
# STATIC_ROOT  =   os.path.join(BASE_DIR, 'staticfiles')
# STATIC_URL = '/static/'

# STATICFILES_DIRS = (
#     os.path.join(PROJECT_ROOT, 'static'),
# )

# STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'

# import dj_database_url 
# prod_db  =  dj_database_url.config(conn_max_age=500)
# DATABASES['default'].update(prod_db)

# django_heroku.settings(locals())

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

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

STATIC_URL = '/static/'

# All additional directories you want Django to look for static files during 'collectstatic'
# outside of the static folder within a django app
# STATICFILES_DIRS = (
#     '/static/',
# )

# This is where files go after you run the collectstatic command
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')

MEDIA_URL = '/media/'

# This is where we want Django to save media files uploaded via the admin panel or by users
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# Will automatically be inside the MEDIA_ROOT folder
CKEDITOR_UPLOAD_PATH = "ckeditor_uploads/"

这是我的 app.yaml 文件

runtime: python39

entrypoint: python3 manage.py migrate && gunicorn -b :$PORT portfolio_backend.wsgi:application --workers 3 --timeout 120

handlers:
- url: /static
  static_dir: static/

- url: /_ah/warmup                        # just serve simple, quick
  static_files: static/img/favicon.ico
  upload: static/img/favicon.ico

- url: /.*
  script: auto

非常感谢任何帮助。谢谢

【问题讨论】:

  • 你想创建一个 GCP 用户 o 你想在哪里创建用户?另外,您使用的是 App Engine Standard 还是 Flex?如果你想在 GCP 中创建用户,我推荐使用 service accountinsted
  • 嘿,我想在将 django 部署到 gcp 后创建一个 django 管理员用户。但我想通了。这样做的方法是在本地连接到 gcp 实例并运行 manage.py 命令
  • 和我提供的答案一样?还是您找到了其他方法?
  • 没有。我找到了其他方法来做到这一点。谢谢
  • 太好了,那么请分享您的解决方案,以便论坛上的每个人都能找到正确的答案:)

标签: python django google-cloud-platform gcloud


【解决方案1】:

您通常在本地部署中使用管理控制台:

python manage.py createsuperuser

然后通过将应用的所有静态文件移动到settings.py中的STATIC_ROOT指定的文件夹中,将所有静态内容收集到一个文件夹中:

python manage.py collectstatic

这必须在部署您的应用程序之前完成,换句话说;在部署之前创建超级用户。

这里有一个quickstart 与 GCP/Phyton/Django 以供更多参考。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 2021-10-13
    • 2011-03-22
    • 2015-02-17
    • 2022-12-24
    • 1970-01-01
    相关资源
    最近更新 更多