Python manage.py migrate doesn't create tables

Viewed 271

The problem is that the python manage.py migrate fails due to the absence of tables in the database, but actually, it should create them. And now in more detail: For several days now I have been trying to solve the problem, so maybe I forgot something from what I did before. I originally had one model

class Product(models.Model):

    code = models.CharField(max_length=50)
    quantity = models.PositiveIntegerField(default=1)
    name = models.CharField(max_length=255)
    slug = AutoSlugField(_('slug'), max_length=255, unique=True, populate_from=('name',))
    technology = models.CharField(max_length=255)
    status = models.CharField(max_length=255, default='Exists')
    description = models.TextField()

Then I needed to make a mptt model from this model to make a product tree and I changed the code like this:

class Product(MPTTModel):

    code = models.CharField(max_length=50)
    quantity = models.PositiveIntegerField(default=1)
    name = models.CharField(max_length=255)
    slug = AutoSlugField(_('slug'), max_length=255, unique=True, populate_from=('name',))
    technology = models.CharField(max_length=255)
    status = models.CharField(max_length=255, default='Exists')
    description = models.TextField()
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, 
    related_name='children')
    
    class MPTTMeta:
        order_insertion_by = ['code']

And the problems started ... The migrations did not want to be applied due to the missing parent _id column. I tried a lot of things then, in the end the following helped me: I manually created the columns parent_id, lft, rght, level, tree_id. And it all worked. Then I decided that for my task it would be better for me to make another subproduct model and make it a MPTTmodel, and return the product to the usual model. Further migrations did not want to apply. That is, new ones were created using the python manage.py makemigrations command, but were not applied by the python manage.py migrate command. Django said that there are no migrations to apply. Although everything was correct in the migration files. Again I had the same problem with missing columns and solved it the same way as last time by adding them manually. It works fine on local machine with existing sqlite DB. But now I am trying to deploy the application and use a postgresql database and Django doesn't want to execute any commands at all, showing an error:

Traceback (most recent call last):
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedTable: relation "product_structure_product" does not exist
LINE 1: ...", "product_structure_product"."description" FROM "product_s...
                                                             ^


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

Traceback (most recent call last):
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/manage.py", line 24, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute
    output = self.handle(*args, **options)
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/core/management/commands/check.py", line 63, in handle
    self.check(
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/core/management/base.py", line 392, in check
    all_issues = checks.run_checks(
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/core/checks/registry.py", line 70, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique
    all_namespaces = _load_all_namespaces(resolver)
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces
    url_patterns = getattr(resolver, 'url_patterns', [])
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/urls/resolvers.py", line 589, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/urls/resolvers.py", line 582, in urlconf_module
    return import_module(self.urlconf_name)
  File "/usr/local/Cellar/python@3.9/3.9.0_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 790, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/LayoutProducts/urls.py", line 23, in <module>
    path('product_structure/', include(('product_structure.urls', 'product_structure'))),
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/urls/conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
  File "/usr/local/Cellar/python@3.9/3.9.0_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 790, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/product_structure/urls.py", line 3, in <module>
    from product_structure.views import structure_page, ProductsListView, ProductDetailView, ProductCreateView, \
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/product_structure/views.py", line 7, in <module>
    from product_structure.forms import ProductCreateForm, ProductCopyForm, ProductsSearchForm
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/product_structure/forms.py", line 38, in <module>
    class ProductCopyForm(forms.ModelForm):
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/product_structure/forms.py", line 41, in ProductCopyForm
    initial = query_set.first()
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/db/models/query.py", line 678, in first
    for obj in (self if self.ordered else self.order_by('pk'))[:1]:
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/db/models/query.py", line 287, in __iter__
    self._fetch_all()
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/db/models/query.py", line 1308, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/db/models/query.py", line 53, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1156, in execute_sql
    cursor.execute(sql, params)
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute
    return super().execute(sql, params)
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/Users/nizhdanchik/PycharmProjects/UpworkProjects/LayoutProducts/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "product_structure_product" does not exist
LINE 1: ...", "product_structure_product"."description" FROM "product_s...

I tried python manage.py makemigrations, python manage.py migrate, python manage.py migrate --fake-initial, python manage.py migrate --fake, python manage.py migrate --run-syncdb, python manage.py migrate --fake product_structure zero, python manage.py migrate --fake zero and nothing happens...Always the same error. I have an app in installed_apps:

import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = 'very secret'


DEBUG = True

ALLOWED_HOSTS = []

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_extensions',
    'debug_toolbar',
    'crispy_forms',
    'django_static_fontawesome',
    'product_structure',
    'mptt',
]

MIDDLEWARE = [
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    '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 = 'LayoutProducts.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 = 'LayoutProducts.wsgi.application'


DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'my_name',
            'USER': 'my_user',
            'PASSWORD': 'my_pass',
        }
    }

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',
    },
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


STATIC_URL = '/static/'
INTERNAL_IPS = [
    '127.0.0.1',
]

CRISPY_TEMPLATE_PACK = 'bootstrap4'

Models.py:

class Product(models.Model):

    code = models.CharField(max_length=50)
    quantity = models.PositiveIntegerField(default=1)
    name = models.CharField(max_length=255)
    slug = AutoSlugField(_('slug'), max_length=255, unique=True, populate_from=('name',))
    technology = models.CharField(max_length=255)
    status = models.CharField(max_length=255, default='Exists')
    description = models.TextField()

    class Meta:
        ordering = ('-name',)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('product_structure:product_detail',
                       args=[self.slug])


class SubProduct(MPTTModel):
    code = models.CharField(max_length=50)
    quantity = models.PositiveIntegerField(default=1)
    name = models.CharField(max_length=255)
    technology = models.CharField(max_length=255, default='None')
    status = models.CharField(max_length=255, default='Exists')
    description = models.TextField()
    product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True, related_name='parent_product')
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')

    class MPTTMeta:
        order_insertion_by = ['code']

    def __str__(self):
        return f'{self.code} {self.name}'

Next will be my migrations files... 0001_initial.py:

from django.db import migrations, models
import django_extensions.db.fields


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Product',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('code', models.CharField(max_length=50)),
                ('quantity', models.PositiveIntegerField(default=1)),
                ('name', models.CharField(max_length=255)),
                ('slug', django_extensions.db.fields.AutoSlugField(blank=True, editable=False, max_length=255, populate_from=('name',), unique=True, verbose_name='slug')),
                ('technology', models.CharField(max_length=255)),
                ('status', models.CharField(default='Exists', max_length=255)),
            ],
            options={
                'ordering': ('-name',),
            },
        ),
    ]

0002_auto_20201103_1338.py:

from django.db import migrations
import django_extensions.db.fields


class Migration(migrations.Migration):

    dependencies = [
        ('product_structure', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='product',
            name='slug',
            field=django_extensions.db.fields.AutoSlugField(blank=True, editable=False, max_length=255, populate_from=('name',), unique=True),
        ),
    ]

0003_auto_20201103_1342.py:

from django.db import migrations
import django_extensions.db.fields


class Migration(migrations.Migration):

    dependencies = [
        ('product_structure', '0002_auto_20201103_1338'),
    ]

    operations = [
        migrations.AlterField(
            model_name='product',
            name='slug',
            field=django_extensions.db.fields.AutoSlugField(blank=True, editable=False, populate_from=('name',), unique=True),
        ),
    ]

0004_auto_20201103_1410.py:

from django.db import migrations, models
import django_extensions.db.fields


class Migration(migrations.Migration):

    dependencies = [
        ('product_structure', '0003_auto_20201103_1342'),
    ]

    operations = [
        migrations.AddField(
            model_name='product',
            name='description',
            field=models.TextField(default=1),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='product',
            name='slug',
            field=django_extensions.db.fields.AutoSlugField(blank=True, editable=False, max_length=255, populate_from=('name',), unique=True, verbose_name='slug'),
        ),
    ]

0005_subproduct.py:

from django.db import migrations, models
import django.db.models.deletion
import mptt.fields


class Migration(migrations.Migration):

    dependencies = [
        ('product_structure', '0004_auto_20201103_1410'),
    ]

    operations = [
        migrations.CreateModel(
            name='SubProduct',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('code', models.CharField(max_length=50)),
                ('quantity', models.PositiveIntegerField(default=1)),
                ('name', models.CharField(max_length=255)),
                ('technology', models.CharField(max_length=255)),
                ('status', models.CharField(default='Exists', max_length=255)),
                ('description', models.TextField()),
                ('lft', models.PositiveIntegerField(editable=False)),
                ('rght', models.PositiveIntegerField(editable=False)),
                ('tree_id', models.PositiveIntegerField(db_index=True, editable=False)),
                ('level', models.PositiveIntegerField(editable=False)),
                ('parent', mptt.fields.TreeForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='children', to='product_structure.subproduct')),
                ('product', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='parent_product', to='product_structure.product')),
            ],
            options={
                'abstract': False,
            },
        ),
    ]

Will appreciate any help. Thanks.

0 Answers
Related