Djagno 3.0 с Python 3.6.12 1054 Ошибка следующего руководства для Django 3.0

#python #python-3.x #linux #pycharm #virtualenv

#python #python-3.x #linux #pycharm #virtualenv

Вопрос:

Всем привет!

Я хотел бы, прежде всего, немного лучше представить себя этому сообществу. я в некоторой степени между новичком и средним уровнем в Python, но продвинут в Linux и MS System Admini. Итак, я знаком с PHP, CSS, HTML, LAMP, XAMP, XMPP, DNS, виртуализацией, облачностью … всем … но, что касается программирования, я начал с Pasqual, затем Visual Basic, и после небольшого изучения Java я сосредоточился на Python.

Процессор: (извините, но я довольно старый skul: i686 (32 бит) ОПЕРАТИВНАЯ память: 4 ГБ ОС: Ubuntu OS 18.04 LTS

  • Тем не менее, давайте перейдем к моей проблеме, ошибка, которую я получаю:

После выполнения некоторого руководства по https://www.youtube.com/watch?v=6ManltU_8iUamp;t=9884s

Я получаю следующее:

 (Django) root@borisdev:/home/Desktop/DjangoRelationships/MyProject# python manage.py shell
Python 3.6.12 (default, Aug 18 2020, 02:08:22) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from MyApp.models import Article, Reporter
>>> r = Reporter(first_name = 'John', last_name = 'Doe', email = 'abc@somemail.com')
>>> r.save()
>>> r1 = Reporter(first_name = 'Boris', last_name = 'Milanovic', email = 'milanvociful@gmail.com')
>>> r1.save()
>>> from datetime import date
>>> a = Article(headline = 'This is my first article', pub_date = date(2020, 10, 10), reporter=r)
>>> a.save()
Traceback (most recent call last):
  File "/home/Desktop/Django/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/home/Desktop/Django/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 73, in execute
    return self.cursor.execute(query, args)
  File "/home/Desktop/Django/lib/python3.6/site-packages/MySQLdb/cursors.py", line 206, in execute
    res = self._query(query)
  File "/home/Desktop/Django/lib/python3.6/site-packages/MySQLdb/cursors.py", line 319, in _query
    db.query(q)
  File "/home/Desktop/Django/lib/python3.6/site-packages/MySQLdb/connections.py", line 259, in query
    _mysql.connection.query(self, query)
MySQLdb._exceptions.OperationalError: (1054, "Unknown column 'reporter_id' in 'field list'")

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

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/Desktop/Django/lib/python3.6/site-packages/django/db/models/base.py", line 754, in save
    force_update=force_update, update_fields=update_fields)
  File "/home/Desktop/Django/lib/python3.6/site-packages/django/db/models/base.py", line 792, in save_base
    force_update, using, update_fields,
  File "/home/Desktop/Django/lib/python3.6/site-packages/django/db/models/base.py", line 895, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "/home/Desktop/Django/lib/python3.6/site-packages/django/db/models/base.py", line 935, in _do_insert
    using=using, raw=raw,
  File "/home/Desktop/Django/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/Desktop/Django/lib/python3.6/site-packages/django/db/models/query.py", line 1254, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "/home/Desktop/Django/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1397, in execute_sql
    cursor.execute(sql, params)
  File "/home/Desktop/Django/lib/python3.6/site-packages/django/db/backends/utils.py", line 98, in execute
    return super().execute(sql, params)
  File "/home/Desktop/Django/lib/python3.6/site-packages/django/db/backends/utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/home/Desktop/Django/lib/python3.6/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/home/Desktop/Django/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/home/Desktop/Django/lib/python3.6/site-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/Desktop/Django/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/home/Desktop/Django/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 73, in execute
    return self.cursor.execute(query, args)
  File "/home/Desktop/Django/lib/python3.6/site-packages/MySQLdb/cursors.py", line 206, in execute
    res = self._query(query)
  File "/home/Desktop/Django/lib/python3.6/site-packages/MySQLdb/cursors.py", line 319, in _query
    db.query(q)
  File "/home/Desktop/Django/lib/python3.6/site-packages/MySQLdb/connections.py", line 259, in query
    _mysql.connection.query(self, query)
django.db.utils.OperationalError: (1054, "Unknown column 'reporter_id' in 'field list'")
>>> 
  

Если потребуются какие-либо дополнительные ресурсы, пожалуйста, дайте мне знать, поскольку до сих пор мой лучший друг «google» смог решить…

Спасибо!

~ Борис

Комментарии:

1. Похоже на отсутствующие или неиспользованные миграции.

2. Я делал миграции и миграции….

3. ОБНОВЛЕНИЕ: (Django) root@borisdev:/home/Desktop/DjangoRelationships/MyProject # питон manage.py makemigrations Никаких изменений не обнаружено (Django) root@borisdev:/home/Desktop/DjangoRelationships/MyProject # питон manage.py Операции переноса для выполнения: Применить все миграции: MyApp, admin, auth, contenttypes, сеансы Запуск миграции: Применение MyApp.0002_auto_20201013_0704… Трассировка (последний последний вызов): Файл «/home/Desktop/Django/lib/python3.6/site-packages/django/db/backends/utils.py «, строка 82, в _execute возвращает self.cursor.execute(sql)

4. Вы активировали приложение в настройках?

Ответ №1:

У меня такая же проблема:

Вот мой settings.py:

 """
Django settings for RelationshipsInDjango project.

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

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

# 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 = '4umiwx4$3p6c2e7!x) 5kk0*s4py5e5n ecn7=efskcer4@6v$@'

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

ALLOWED_HOSTS = []


# Application definition

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

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


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydjango',
        'USER': 'debian-sys-maint',
        'PASSWORD': '6LJl7CAz9Lyuxxxx',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}


# 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/'