簡體   English   中英

Django 到 Heroku,如何將 sqlite3 數據遷移到 postgres

[英]Django to Heroku, How to migrate sqlite3 data to postgres

我試圖在 heroku 上托管一個網站,但我不斷收到此錯誤

文件“/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py”,第 84 行,在 _execute 中返回 self.cursor.execute(sql, params) django.db .utils.ProgrammingError:關系“home_product”不存在第1行:...home_product”。“價格”,“home_product”。“slug” FROM“home_prod ...

每當我嘗試使用

heroku run python
manage.py migrate -a appname

我主要將此視頻用作托管的參考。

還有這個 StackOverflow 問題這篇文章也沒有對這個問題有太多的了解。

這是我的settings.py

"""
Django settings for Corbett_Jewelry project.

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

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

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


from pathlib import Path
import os
import django_heroku
import dj_database_url
from decouple import config
import psycopg2

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

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

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False'


ALLOWED_HOSTS = ['127.0.0.1']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'home'
]

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',
    'whitenoise.middleware.WhiteNoiseMiddleware',
]

ROOT_URLCONF = 'Corbett_Jewelry.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'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 = 'Corbett_Jewelry.wsgi.application'

# Password validation
# https://docs.djangoproject.com/en/3.1/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.1/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.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True)

db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

django_heroku.settings(locals())

我的models.py

from django.db import models


class Product(models.Model):
    name = models.CharField(max_length=100)
    image = models.ImageField(blank=True)
    desc = models.TextField()
    price = models.IntegerField()
    slug = models.SlugField(unique=True, default=None)

    def __str__(self):
        return self.name

class Images(models.Model):
    product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE)
    img = models.ImageField(upload_to='images/')

    def __str__(self):
        return self.product.name

    
class Beads(models.Model):
    name = models.CharField(max_length=200)
    price = models.IntegerField()
    img = models.ImageField(upload_to='beads/')

我的檔案:

web: gunicorn Corbett_Jewelry.wsgi

我的requirements.txt

asgiref==3.4.1
cycler==0.10.0
dj-database-url==0.5.0
Django==3.2.9
django-heroku==0.3.1
gunicorn==20.1.0
kiwisolver==1.3.2
matplotlib==3.4.3
numpy==1.21.2
Pillow==8.3.2
psycopg2==2.9.2
pyparsing==2.4.7
python-dateutil==2.8.2
python-decouple==3.5
pytz==2021.3
selenium==3.141.0
six==1.16.0
sqlparse==0.4.2
urllib3==1.26.7
whitenoise==5.3.0

我不知道您可能還需要什么信息來解決這個問題。 我很高興提供任何信息,因為我已經為此苦苦掙扎了一周。

@Gamingapple ...正如您在評論中所問的那樣,我將嘗試為您的問題提供我能想到的所有可能的解決方案。

我從未使用過 Heroku,但這是我會嘗試的第一個解決方案

1. A quick read from Heroku's help docs is showing you perhaps are not running migrations in the way that Heroku thinks are best practices for migrations: https://help.heroku.com/GDQ74SU2/django-migrations there (more-or- less) 意味着您應該在本地運行遷移,向上推到 Git,然后 Heroku 將在部署時自動運行遷移,其中指出:

Then, add the following as the first line in your Procfile:

release: python manage.py migrate

但請注意,這也意味着您應該在本地開發中使用 Postgres,而不是 SQLite(如您的標題所示)。

- 除此之外,您似乎正在嘗試按應用程序運行遷移: manage.py migrate -a appname , Django 確實有一些需要運行的常規遷移,所以我只是嘗試manage.py migrate

2.您在評論中注意到 PyPi 的dj_database_url package: https://pypi.org/project/dj-database-url/中的dj_database_url.config()返回一個空字典。 對我來說,如果沒有額外的信息,我會說這是您的問題所在,當您手動嘗試在 Heroku 實例中運行migrate時; 沒有可查找或連接的數據庫。 為了解決這個問題,我將刪除dj_database_url的使用(因為我也沒有使用它,我們正在調試),並為 Django 的DATABASES手動編寫我的連接字符串,如下所示:

pip install psycopg2或確保它在要求/安裝中。

將設置中的DATABASES屬性更改為手動編寫,以便您知道它是什么(我們正在調試,所以也許在您啟動它之后,您可以使密碼收集更安全,例如作為環境變量)

DATABASES = {
   'default': {
       'ENGINE': 'django.db.backends.postgresql',
       'NAME': '[HEROKU DB NAME]',
       'USER': '[HEROKU DB USERNAME]',
       'PASSWORD': '[HEROKU PASSWORD]',
       'HOST': '{HEROKU HOST IP OR NAME FOR YOUR DB]',
       'PORT': '[HEROKU DB PORT]',
   }
}

現在正確地運行遷移命令:

python manage.py makemigrations

python manage.py migrate

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM