django.db.utils.OperationalError: near "CASCADE": syntax error when making a pull request in Github

django.db.utils.OperationalError: near "CASCADE": syntax error when making a pull request in Github

我正在尝试使用 Heroku 部署一个 django 网站。 当我运行python3 manage.py runserver时,一切正常。但是当我将它推送到 github 并发出拉取请求时,我有一个测试我的代码的操作并且我 运行 进入该错误。

Using existing test database for alias 'default'...
Found 7 test(s).
System check identified no issues (0 silenced).
.......
Alicia
----------------------------------------------------------------------
Tiffany
Barbara
Ran 7 tests in 1.319s

OK
Taylor
Dr.
Wanda
Jacob
Traceback (most recent call last):
  File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/db/backends/utils.py", line 83, in _execute
    return self.cursor.execute(sql)
  File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 414, in execute
    return Database.Cursor.execute(self, query)
sqlite3.OperationalError: near "CASCADE": syntax error

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line
    utility.execute()
  File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/commands/test.py", line 24, in run_from_argv
    super().run_from_argv(argv)
  File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/base.py", line 373, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/base.py", line 417, in execute
    output = self.handle(*args, **options)
  File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/commands/test.py", line 59, in handle
    failures = test_runner.run_tests(test_labels)
  File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/test/runner.py", line 941, in run_tests
    self.teardown_databases(old_config)
  File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django_on_heroku/core.py", line 33, in teardown_databases
    self._wipe_tables(connection)
  File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django_on_heroku/core.py", line 27, in _wipe_tables
    cursor.execute(f"DROP TABLE IF EXISTS {table_name} CASCADE")
  File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/db/backends/utils.py", line 67, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/db/backends/utils.py", line 83, in _execute
    return self.cursor.execute(sql)
  File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 414, in execute
    return Database.Cursor.execute(self, query)
django.db.utils.OperationalError: near "CASCADE": syntax error
Error: Process completed with exit code 1.

在我创建 Procfile 并将以下更改添加到我的 seetings.py 后出现此错误:

import django_on_heroku STATIC_ROOT = os.path.join(BASE_DIR, 'static') django_on_heroku.settings(locals())

查看下面的完整 settings.py:

"""
Django settings for website project.

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

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

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

from pathlib import Path
import os
import sys
import django_on_heroku
from django.contrib.messages import constants as messages

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TESTING = len(sys.argv)>1 and sys.argv[1] == 'test'

ALLOWED_HOSTS = []

AUTH_USER_MODEL="register.User"

LOGIN_URL ="/login"


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'register',
    'main',
    'crispy_forms',
]

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 = 'website.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 = 'website.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.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/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Email config

EMAIL_FROM_USER=os.environ.get('EMAIL_FROM_USER')
EMAIL_HOST='smtp.gmail.com'
EMAIL_HOST_USER=os.environ.get('EMAIL_FROM_USER')
EMAIL_HOST_PASSWORD=os.environ.get('EMAIL_HOST_PASSWORD')
EMAIL_USE_TLS=True
EMAIL_PORT=587



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

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

CRISPY_TEMPLATE_PACK="bootstrap4"

LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = "/"

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

MESSAGE_TAGS = {
    messages.DEBUG: 'alert-info',
    messages.ERROR: 'alert-danger',
    messages.SUCCESS: 'alert-success',
    messages.WARNING: 'alert-warning',
    messages.INFO: 'alert-info',
}

django_on_heroku.settings(locals())

和下面的 Procfile:

release: python3 manage.py makemigrations
release: python3 manage.py migrate


web: gunicorn website.wsgi

如果您有解决方法,请告诉我。 谢谢。

SQLite 不支持 django_on_heroku 包中的 SQL 语法,这就是您看到错误的原因。

您可以在 DROP TABLE 上查看 SQLite here 的详细信息,但要引用该页面;

SQLite doesn’t support the CASCADE and RESTRICT keywords, which are included in the SQL standard, and are supported by some other RDBMSs (such as PostgreSQL).

很有可能您的服务器是 运行 mysql 或 postgres,但您的测试使用 SQLite.

您提到 github 工作流程是问题发生的地方,所以我希望在该工作流程中使用 mysql 或 postgres。你可以看到这个 here.

的例子