django.db.utils.OperationalError:“CASCADE”附近:在 Github 中发出拉取请求时出现语法错误

发布于 2025-01-10 08:55:00 字数 8383 浏览 0 评论 0原文

我正在尝试使用 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

如果您知道如何解决此问题,请告诉我。 谢谢。

I'm trying to deploy a django website with Heroku.
When I run python3 manage.py runserver, everything works normally. But when I push it to github and make a pull request, I have an action that tests my code and I run into that error.

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.

This error appeared after I created a Procfile and added the following changes to my seetings.py:

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

See full settings.py below:

"""
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())

and Procfile below:

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


web: gunicorn website.wsgi

If you have an idea how to solve this, please let me know.
Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤芳又自赏 2025-01-17 08:55:00

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

您可以在此处查看有关 SQLite 的 DROP TABLE 的详细信息,但是引用该页面;

SQLite 不支持 CASCADE 和 RESTRICT 关键字,这些关键字包含在 SQL 标准中,但受其他一些 RDBMS(例如 PostgreSQL)。

您的服务器很可能正在运行 mysql 或 postgres,但您的测试使用 SQLite。

您提到 github 工作流程是问题发生的地方,所以我希望在该工作流程中使用 mysql 或 postgres。您可以在此处查看示例。

SQLite doesn't support that SQL syntax from the django_on_heroku package, which is why you see the error.

You can see details on DROP TABLE for SQLite here, but to quote that page;

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).

There's a good chance that your server is running mysql or postgres, but your tests use SQLite.

You've mentioned that a github workflow is where the problem occurs, so I'd look to use mysql or postgres in that workflow. You can see examples of this here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文