OperationalError: no such table: django_content_type and django_session

merryfistmas

I cannot access my app, when I enter the URL, it gives me the error

OperationalError: no such table: django_session

This usually means I need to migrate, or delete my sqlite database and redo migrations, so I did that multiple times. I deleted everything in the migrations folder and sqlite3.db and ran:

python manage.py makemigrations app_name
python manage.py migrate app_name

No errors yet. Then after creating a superuser I run:

python manage.py runserver

It tells me 18 migrations have not been made, which I was able to fix with:

python manage.py migrate --fake

I try the site and again I get the no such table: django_session error.

I read this thread Django: no such table: django_session and tried everything in it, including the approved solution, same error.

Also, when I try to run the migrate command again, I get this error

OperationalError: no such table: django_content_type

so I went to this thread sqlite3.OperationalError: no such table: django_content_type

once again, the solutions that worked for them did not work for me.

This problem started after we migrated to MySQL, I tried to switch databases using a .env file, but ran into these problems, so I tried to switch back to sqlite so I can at least work on the project. The team is in the middle of moving to MySQL, and we have people working successfully with both databases, so it shouldn't be a database issue.

Here is my settings.py file:

import os
from pathlib import Path
from django.contrib.messages import constants as message_constants

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

SECRET_KEY = os.environ.get("DJ_SECRET_KEY", default="Testing")
DEBUG = os.environ.get("DJ_DEBUG", default=True)
ALLOWED_HOSTS = ["redonkulator.apps.dev.mach9.usmc.mil", "localhost", "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",
    "redonkulator_app.apps.RedonkulatorAppConfig",
    "jquery",
    "debug_toolbar",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.middleware.common.CommonMiddleware",
    "debug_toolbar.middleware.DebugToolbarMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
]

ROOT_URLCONF = "iiimef_project.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": ["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",
            ],
        },
    },
]

AUTH_USER_MODEL = "redonkulator_app.MlptUsers"

WSGI_APPLICATION = "iiimef_project.wsgi.application"

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

DATABASES = {
    "default": {
        "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"),
        "NAME": os.environ.get(
            "SQL_DATABASE",
            os.path.join(BASE_DIR, "db.sqlite3"),
        ),
        "USER": os.environ.get("SQL_USER", "user"),
        "PASSWORD": os.environ.get("SQL_PASSWORD", "password"),
        "HOST": os.environ.get("SQL_HOST", "localhost"),
        "PORT": os.environ.get("SQL_PORT", "5432"),
    }
}

# Password validation
# https://docs.djangoproject.com/en/3.2/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.2/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.2/howto/static-files/

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

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

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

LOGIN_REDIRECT_URL = ""
LOGOUT_REDIRECT_URL = "/about"
LOGIN_URL = "/login"

MESSAGE_STORAGE = "django.contrib.messages.storage.cookie.CookieStorage"

# needed to overwrite bootsrap classes
MESSAGE_TAGS = {
    message_constants.DEBUG: "debug",
    message_constants.INFO: "info",
    message_constants.SUCCESS: "success",
    message_constants.WARNING: "warning",
    message_constants.ERROR: "danger",
}


INTERNAL_IPS = [
    "127.0.0.1",
]

I have session and contenttype in my installed apps and sessions in my middleware, is there anything in here that looks obviously wrong?

Here is my .env

DJ_SECRET_KEY=super-secret-key
DJ_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] 0.0.0.0 *
DJ_DEBUG=True
SQL_DATABASE=redonkulator
SQL_ENGINE=django.db.backends.mysql
SQL_USER=[myusername]
SQL_PASSWORD=[mypassword]
SQL_HOST=localhost
SQL_PORT=3306

I know that this .env won't work with my settings, and that's okay as I'm just trying to get sqlite to work for now.

One more thing, starting today, slightly after this problem started, every django import is underlined in yellow. For example "django.contrib.messages" in settings.py is underlined, however I don't get a module import error, so I don't think that's the issue.

Finally, here is the traceback for the content_type error:

Traceback (most recent call last):
  File "C:\Users\dwill\Documents\GitHub\MLPT\manage.py", line 22, in <module>
    main()
  File "C:\Users\dwill\Documents\GitHub\MLPT\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\base.py", line 398, in execute
    output = self.handle(*args, **options)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\base.py", line 89, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\commands\migrate.py", line 268, in handle
    emit_post_migrate_signal(
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\sql.py", line 42, in emit_post_migrate_signal
    models.signals.post_migrate.send(
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\dispatch\dispatcher.py", line 180, in send
    return [
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\dispatch\dispatcher.py", line 181, in <listcomp>
    (receiver, receiver(signal=self, sender=sender, **named))
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\auth\management\__init__.py", line 42, in create_permissions
    create_contenttypes(app_config, verbosity=verbosity, interactive=interactive, using=using, apps=apps, **kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\contenttypes\management\__init__.py", line 119, in create_contenttypes
    content_types, app_models = get_contenttypes_and_models(app_config, using, ContentType)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\contenttypes\management\__init__.py", line 94, in get_contenttypes_and_models   
    content_types = {
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\query.py", line 280, in __iter__
    self._fetch_all()
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\query.py", line 51, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\sql\compiler.py", line 1175, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 98, in execute
    return super().execute(sql, params)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: django_content_type

and the django session error:

Traceback (most recent call last):
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
    return Database.Cursor.execute(self, query, params)

The above exception (no such table: django_session) was the direct cause of the following exception:
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\admin\sites.py", line 414, in login
    return LoginView.as_view(**defaults)(request)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
    return bound_method(*args, **kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper
    return view(request, *args, **kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
    return bound_method(*args, **kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
    return bound_method(*args, **kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\auth\views.py", line 63, in dispatch
    return super().dispatch(request, *args, **kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
    return handler(request, *args, **kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\generic\edit.py", line 142, in post
    return self.form_valid(form)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\auth\views.py", line 92, in form_valid
    auth_login(self.request, form.get_user())
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\auth\__init__.py", line 111, in login
    request.session.cycle_key()
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\sessions\backends\base.py", line 344, in cycle_key
    self.create()
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\sessions\backends\db.py", line 51, in create
    self._session_key = self._get_new_session_key()
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\sessions\backends\base.py", line 196, in _get_new_session_key
    if not self.exists(session_key):
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\sessions\backends\db.py", line 47, in exists
    return self.model.objects.filter(session_key=session_key).exists()
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\query.py", line 808, in exists
    return self.query.has_results(using=self.db)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\sql\query.py", line 550, in has_results
    return compiler.has_results()
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\sql\compiler.py", line 1145, in has_results
    return bool(self.execute_sql(SINGLE))
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\sql\compiler.py", line 1175, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\debug_toolbar\panels\sql\tracking.py", line 198, in execute
    return self._record(self.cursor.execute, sql, params)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\debug_toolbar\panels\sql\tracking.py", line 133, in _record
    return method(sql, params)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 98, in execute
    return super().execute(sql, params)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
    return Database.Cursor.execute(self, query, params)

Exception Type: OperationalError at /admin/login/
Exception Value: no such table: django_session
stackdon

Try avoiding the .env file to rule that out.

Update settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'DBNAME',
        'USER': 'USER',
        'PASSWORD': 'PASS',
        'HOST': '127.0.0.1',
        'PORT': 3306
    }
}

If this works then we have found the source of the problem and should double-check the location of the .env file and work backwards from there.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

OperationalError, no such column. Django

How can I resolve 'django_content_type already exists'?

How can I resolve 'django_content_type already exists'?

Django: OperationalError No Such Table

Django 1.7 django.db.utils.OperationalError: no such table: auth_customuser

Django column "name" of relation "django_content_type" does not exist

Django: OperationalError at /admin/

Clearing sessions in django_session table without logging out current users

OperationalError: no such table

Is it safe to delete the `django_session` table if my Django app is using a cache-based session backend?

ProgrammingError: relation "django_session" does not exist

Makemigrations error : django.db.utils.OperationalError: no such table

Django OperationalError: no such column

Django 3.1: OperationalError - No Such Column/Table

Django test fails with 'django.db.utils.ProgrammingError: relation "django_content_type" does not exist'

Django OperationalError table has no column named user_id

Is it safe to share `auth_user` and `django_session` table for intranet Django projects?

OperationalError at : "site" Exception Value: No such Table django_site

Django testing on separate database giving "OperationalError: no such table: auth_user"

Django migrate django.db.utils.OperationalError: no such table:

Django: sqlite3.OperationalError: no such table in python shell

django.db.utils.OperationalError: no such table: Schedule_swimmingscore

Django OperationalError: no such column: on pythonanywhere

Change to PostgreSQL raise django.db.utils.OperationalError: no such table Error

Django 2.2 - django.db.utils.OperationalError: no such table

Django deployment on heroku throws django.db.utils.OperationalError: no such table: auth_user

django.db.utils.OperationalError: no such table: store_product

unable to create superuser in django getting error "django.db.utils.OperationalError: no such table: auth_user"

relation "django_content_type" already exists django

TOP Ranking

HotTag

Archive