django.db.utils.OperationalError: no such table: django_session - django

Premise: I'm a starter[Plz be kind and patient]
When i try to run commands in the terminal like:
python manage.py makemigrations audioma_manager
or
python manage.py runserver
or
python manage.py migrate
or
python manage.py --run-syncdb
where
audioma_manager is the name of my project
I tried also with the name of my app
I get this excetion code, I searched lots on the net but any kind of solution works with my problem:
Traceback (most recent call last):
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: django_session
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 "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle
self.check(databases=[database])
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 423, in check
databases=databases,
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\urls\resolvers.py", line 412, in check
for pattern in self.url_patterns:
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\39371\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\39371\audioma_manager\audioma_manager\urls.py", line 20, in <module>
path('transcription_form/', include('transcription_form.urls')),
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\urls\conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\39371\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\39371\audioma_manager\transcription_form\urls.py", line 2, in <module>
from .views import upload
File "C:\Users\39371\audioma_manager\transcription_form\views.py", line 4, in <module>
from .forms import UploadForm
File "C:\Users\39371\audioma_manager\transcription_form\forms.py", line 5, in <module>
source_choice=GetAPISources.call_api(GetAPISources,endpoint='sources')
File "C:\Users\39371\audioma_manager\transcription_form\client_transcpition_api.py", line 48, in call_api
session_stored = s.load()
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\contrib\sessions\backends\db.py", line 43, in load
s = self._get_session_from_db()
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\contrib\sessions\backends\db.py", line 34, in _get_session_from_db
expire_date__gt=timezone.now()
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\models\query.py", line 431, in get
num = len(clone)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\models\query.py", line 262, in __len__
self._fetch_all()
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users\39371\AudioManVenv\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\39371\AudioManVenv\lib\site-packages\django\db\models\sql\compiler.py", line 1175, in execute_sql
cursor.execute(sql, params)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "C:\Users\39371\AudioManVenv\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\39371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\39371\AudioManVenv\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_session
This is my setting file( I'm using django-environ to keep secret some variables):
import environ
import os
from pathlib import Path
env = environ.Env(
# set casting, default value
DEBUG=(bool, False)
)
DJANGO_SETTINGS_MODULE="audioma_manager.settings"
# Set the project base directory
BASE_DIR = Path(__file__).resolve().parent.parent
# Take environment variables from .env file
environ.Env.read_env(os.path.join(BASE_DIR, '.env'))
# False if not in os.environ because of casting above
DEBUG = env('DEBUG')
# Raises Django's ImproperlyConfigured
# exception if SECRET_KEY not in os.environ
SECRET_KEY = env('SECRET_KEY')
# Parse database connection url strings
# like psql://user:pass#127.0.0.1:8458/db
#For production
#DATABASES = {
# read os.environ['DATABASE_URL'] and raises
# ImproperlyConfigured exception if not found
#
# The db() method is an alias for db_url().
'default': env.db(),
# read os.environ['SQLITE_URL']
#'extra': env.db_url(
#'SQLITE_URL',
#default='sqlite:///tmp/my-tmp-sqlite.db'
# )
#}
CACHES = {
# Read os.environ['CACHE_URL'] and raises
# ImproperlyConfigured exception if not found.
#
# The cache() method is an alias for cache_url().
'default': env.cache(),
#instance of sensibile data from .env file
}
API_URL= {
env('API_URL')
}
API_VERSION={
env('API_VERSION')
}
API_USERNAME={
env('API_USERNAME')
}
API_PASSWORD={
env('API_PASSWORD')
}
API_ENDPOINT_SOURCES={
env('API_ENDPOINT_SOURCES')
}
DEFAULT_DIR_PATH={
env('DEFAULT_DIR_PATH')
}
DEFAULT_NAME_FILE_PATTERN={
env('DEFAULT_NAME_FILE_PATTERN')
}
API_ENDPOINT_LOGIN={
env('API_ENDPOINT_LOGIN')
}
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'transcription_form',
'corsheaders',
'rest_framework'
]
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',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware'
]
ROOT_URLCONF = 'audioma_manager.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 = 'audioma_manager.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
#Local db for tests
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
'USER': 'USER',
'PASSWORD': 'PASS',
'HOST': '127.0.0.1',
'PORT': 3306
}
}
# 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',
},
]
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'INFO',
'class': 'logging.FileHandler',
'filename': '\\Users\\39371\\audioma_manager\\audioma_manager\\logs\\debug.log',
},
},
'loggers': {
'transcription_form.client_transcription_api': {
'handlers': ['file'],
'level': 'INFO'
},
},
}
# 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/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
'http://localhost:8080',
)
My client:
from audioma_manager.settings import API_ENDPOINT_LOGIN, API_PASSWORD, API_URL, API_USERNAME, API_VERSION
from django.contrib.sessions.backends.db import SessionStore
import requests
from requests.structures import CaseInsensitiveDict
#class API management
class GetAPISources:
#authentication to aziendal api
def auth_api(self):
url = API_URL + API_VERSION + API_ENDPOINT_LOGIN
auth_email = API_USERNAME
auth_password = API_PASSWORD
list_of_auth = [auth_email,auth_password]
response= requests.post(url,list_of_auth)
if response.status_code==400:
#manage exception code; return null
return False
token=response['token']
#instance of SessionStore
s=SessionStore()
s['auth_token']=token
# saves the current token
s.save()
#implement a method who calls API endpoint from InfojuiceAPi with representation=1
def call_api(self,endpoint):
api_repr='&representation=1'
s=SessionStore()
session_stored = s.load()
auth_token=session_stored['auth_token']
#used endpoint so i can customize the type of endpoint everytime i call the function
#example--> endpoint='/sources' ; endpoint='/customers'
url = API_URL + API_VERSION + endpoint + api_repr
headers = CaseInsensitiveDict()
headers["Accept"]="application/json"
headers["Authorization"]="token " + auth_token
response= requests.get(url,headers=headers)
if response.status_code==401:
self.auth_api()
self.call_api(endpoint)
return response
My Model:
from django.db import models
# Create your models here.
class Transcription(models.Model):
id = models.BigAutoField
file_name = models.CharField(max_length=10000)
created_at = models.DateTimeField(auto_now_add=True, name='created_at')
updated_at = models.DateTimeField(auto_now=True, name='updated_at')
def __str__(self):
return self.file_name
My Form:
from django import forms
from .client_transcpition_api import GetAPISources
source_choice=GetAPISources.call_api(GetAPISources,endpoint='sources')
class UploadForm(forms.Form):
lang = forms.CharField(label='Lingua', max_length=100, help_text = "Inserisci la lingua del contenuto")
source = forms.CharField(label='Fonte', help_text = "Seleziona la fonte del contenuto" , widget=forms.Select(choices=source_choice))
data = forms.DateField(label='data', help_text = "Seleziona la data del contenuto ", max_length=100)
time = forms.TimeField(label='ora', help_text = "Seleziona l' orario del contenuto", max_length=100)
extension = forms.CharField(label='estensione', help_text = "Seleziona l'estensione del contenuto", max_length=100)
file = forms.FileField(label='file da caricare', help_text = "Seleziona il file da mandare in trascrizione")
My views:
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadForm
def upload(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = UploadForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# redirect to a new URL:
#this url is only temp, evaluate better how to do
return HttpResponseRedirect('/thanks/')
else:
form = upload()
return render(request, 'upload.html', {'form': form})
My template:
<!DOCTYPE html>
{% Block Content %}
<h2>Upload</h2>
<form enctype="multipart/form-data" method="post" action="/foo/">
<!-- we need to use this token bc Django makes security controls and requires this token
to be recognize as trust source of code -->
{% csrf_token %}
{{form}}
<input type="file" name="recupero">
<button type="submit">Invio</button>
</form>
In my project I want to:
1)Create repositories, new Django project and first commit.
2)Install Django Environ to upload configurations via .env files.
The configuration must allow you to configure:
authentication to Aziendal API (URL, version, username, password)
path directory for saving the new file to be transcribed
filename pattern (with placeholder for replacing the various components, such as date, source name, title, language, time)
3)Create the Transcription model to save information about content sent in transcription.
Scheme:
ID
file_name Method (String)
created_at (Datetime)
updated_at (Datetime)
4)
Implement a mini client to Aziendal API for THE GET retrieval of sources filtered by name and with the query parameter for rapresentation retrieval.
Use the authentication configured in the configuration file.
5)
Implement a page with a form to load a new transcript with the following fields:
date (date)
source (select sources taken from API)
language (select taken from the configuration)
title
possible profile (optional)
Plz help a young starter.
If u need some source code of my project, just ask:)
Thx for help
xoxo

The most pressing problem here is that you're doing a database call at import time by trying to load a session via
File "C:\Users\39371\audioma_manager\transcription_form\forms.py", line 5, in <module>
source_choice=GetAPISources.call_api(GetAPISources,endpoint='sources')
File "C:\Users\39371\audioma_manager\transcription_form\client_transcpition_api.py", line 48, in call_api
session_stored = s.load()
File "C:\Users\39371\AudioManVenv\lib\site-packages\django\contrib\sessions\backends\db.py", line 43, in load
s = self._get_session_from_db()
which is a big no-no in Django and leads to a chicken-and-egg problem:
you need to make migrations and run migrations to create database tables
Django needs to be able to import your app to do so
your app tries to do a database query from an as-of-yet-nonexistent table (since it's not been migrated yet).
You'll need to do that source_choice at e.g. __init__ time for the form, not at import time.
For the time being, you can replace the source_choice=... line with just source_choice=[] – you won't have any sources to choose from, but you can get your migrations running.
That aside, that session-related code looks strange, especially since you're trying to do so outside of a request context. There will be no valid session to load in that case, since there is no request either. I think you may be confusing Django sessions with whatever the API you're using requires.

Related

Error running migration after changing to spatialite db

I want to use geographical point in my django app therefor i changed the database engine to spatialite
settings.py
"""
Django settings for server project.
Generated by 'django-admin startproject' using Django 4.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.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/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-+r-63iiele&p+irgsm2ojoayyrk2^6($no8%x+^(32s3wvpk7b'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'django.contrib.gis',
'hiketracking.apps.HiketrackingConfig',
'rest_framework',
]
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 = 'server.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 = 'server.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
"ENGINE": "django.contrib.gis.db.backends.spatialite",
'NAME': BASE_DIR / 'db.sqlite3',
},
}
# Password validation
# https://docs.djangoproject.com/en/4.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/4.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
SPATIALITE_LIBRARY_PATH = '/usr/local/lib/mod_spatialite.dylib'
# Absolute filesystem path to the directory that will hold user-uploaded files.
MEDIA_ROOT = BASE_DIR
model.py
from django.contrib.gis.db import models
# Create your models here.
class Hike(models.Model):
title = models.CharField(max_length=30, unique=True)
length = models.IntegerField()
expected_time = models.IntegerField()
ascent = models.IntegerField()
start_point = models.PointField()
end_point = models.PointField()
description = models.CharField(max_length=200)
track_file = models.FileField(upload_to='tracks')
class HikeReferencePoint(models.Model):
hike = models.ForeignKey(Hike, on_delete=models.CASCADE)
reference_point = models.PointField()
after i run migration i get the fallowing error
Tracking file by folder pattern: migrations
Operations to perform:
Apply all migrations: admin, auth, contenttypes, hiketracking, sessions, sites
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add...Traceback (most recent call last):
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: error in trigger ISO_metadata_reference_row_id_value_insert: no such column: rowid
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm/django_manage.py", line 52, in <module>
run_command()
File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm/django_manage.py", line 46, in run_command
run_module(manage_file, None, '__main__', True)
File "/usr/local/Cellar/python#3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/runpy.py", line 224, in run_module
return _run_module_code(code, init_globals, run_name, mod_spec)
File "/usr/local/Cellar/python#3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/runpy.py", line 96, in _run_module_code
_run_code(code, mod_globals, init_globals,
File "/usr/local/Cellar/python#3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/runpy.py", line 86, in _run_code
exec(code, run_globals)
File "/Users/md/Desktop/collage/soft2MainProject/server/manage.py", line 22, in <module>
main()
File "/Users/md/Desktop/collage/soft2MainProject/server/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute
output = self.handle(*args, **options)
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/core/management/base.py", line 96, in wrapped
res = handle_func(*args, **kwargs)
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 349, in handle
post_migrate_state = executor.migrate(
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 135, in migrate
state = self._migrate_all_forwards(
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards
state = self.apply_migration(
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 252, in apply_migration
state = migration.apply(state, schema_editor)
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/db/migrations/migration.py", line 130, in apply
operation.database_forwards(
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/db/migrations/operations/fields.py", line 235, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/schema.py", line 174, in alter_field
super().alter_field(model, old_field, new_field, strict=strict)
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 788, in alter_field
self._alter_field(
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/schema.py", line 457, in _alter_field
self._remake_table(model, alter_field=(old_field, new_field))
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/schema.py", line 347, in _remake_table
self.alter_db_table(
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/contrib/gis/db/backends/spatialite/schema.py", line 153, in alter_db_table
super().alter_db_table(model, old_db_table, new_db_table, disable_constraints)
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/schema.py", line 121, in alter_db_table
super().alter_db_table(model, old_db_table, new_db_table)
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 606, in alter_db_table
self.execute(
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 199, in execute
cursor.execute(sql, params)
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 103, in execute
return super().execute(sql, params)
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute
with self.db.wrap_database_errors:
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
File "/Users/md/Desktop/collage/soft2MainProject/server/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: error in trigger ISO_metadata_reference_row_id_value_insert: no such column: rowid
I have runed makemigration before migration.
my django version is 4.3.1
i have tryed deleting the database and befor migration i have run makemigration. if I only migrate my app it will work but i need the admin panel there for i need to find a way to fix this thank you

First project of Django with mongodb getting django.db.utils.DatabaseError

I created my first with MongoDB with Django
while during the setup I am getting this problem error
Internal Server Error: /api/v1/device/
Traceback (most recent call last):
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 856, in parse
return handler(self, statement)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 928, in _insert
query.execute()
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 397, in execute
res = self.db[self.left_table].insert_many(docs, ordered=False)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/pymongo/collection.py", line 761, in insert_many
blk.execute(write_concern, session=session)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/pymongo/bulk.py", line 528, in execute
return self.execute_command(generator, write_concern, session)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/pymongo/bulk.py", line 363, in execute_command
_raise_bulk_write_error(full_result)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/pymongo/bulk.py", line 140, in _raise_bulk_write_error
raise BulkWriteError(full_result)
pymongo.errors.BulkWriteError: batch op errors occurred, full error: {'writeErrors': [{'index': 0, 'code': 11000, 'errmsg': 'E11000 duplicate key error collection: farmos.device index: __primary_key__ dup key: { id: null }', 'keyPattern': {'id': 1}, 'keyValue': {'id': None}, 'op': {'device_id': 2, 'device_name': None, 'device_status': 'new', 'device_actions': True, 'device_token': True, '_id': ObjectId('63182c4ee9afd58ca7855029')}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []}
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/cursor.py", line 56, in execute
params)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 783, in __init__
self._query = self.parse()
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/sql2mongo/query.py", line 868, in parse
raise exe from e
djongo.exceptions.SQLDecodeError:
Keyword: None
Sub SQL: None
FAILED SQL: INSERT INTO "device" ("device_id", "device_name", "device_status", "device_actions", "device_token") VALUES (%(0)s, %(1)s, %(2)s, %(3)s, %(4)s)
Params: [2, None, 'new', True, True]
Version: 1.3.3
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/cursor.py", line 59, in execute
raise db_exe from e
djongo.database.DatabaseError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/home/adarsh/farmos/farmos/persistance_layer/mongodb/device_operations.py", line 22, in create
serializer_user.save()
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/serializers.py", line 212, in save
self.instance = self.create(validated_data)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/serializers.py", line 962, in create
instance = ModelClass._default_manager.create(**validated_data)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/query.py", line 433, in create
obj.save(force_insert=True, using=self.db)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/base.py", line 746, in save
force_update=force_update, update_fields=update_fields)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/base.py", line 784, in save_base
force_update, using, update_fields,
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/base.py", line 887, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/base.py", line 926, in _do_insert
using=using, raw=raw,
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/query.py", line 1204, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1391, in execute_sql
cursor.execute(sql, params)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/home/adarsh/farmos/venv/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/adarsh/farmos/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/djongo/cursor.py", line 59, in execute
raise db_exe from e
django.db.utils.DatabaseError
directory-path
farmos
/device -> model,view,serializer
/farm -> model,view,serializer
/persistances_layer -> model,view,serializer
/farmos -> settings.py, urls.py, utils.py
here Is my settings.py file
please let m know if there is any mistake that I am making here
"""
Django settings for farmos project.
Generated by 'django-admin startproject' using Django 3.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-v-iu2x3pd&m0qap1k%y=8jua12v$adi*r132uha%&jdsp781(&'
# 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',
'rest_framework',
'rest_framework.authtoken',
'device.apps.DeviceConfig',
'farm.apps.FarmConfig',
'persistance_layer.apps.PersistanceLayerConfig'
]
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 = 'farmos.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 = 'farmos.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'farmos',
'CLIENT': {
'host': 'mongodb://srv13.absolute.ag:27017',
# 'username': 'user1',
# 'password': 'pass1',
# 'authSource': 'admin1',
# 'authMechanism': 'SCRAM-SHA-1',
}
}
}
# 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',
},
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
# 'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'COERCE_DECIMAL_TO_STRING': False,
# 'EXCEPTION_HANDLER': 'farmos.utils.custom_exception_handler',
}
# 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/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
here is the requirement.txt file packages that i am using
weasyprint~=52.5
boto3==1.10.41
django-3-jet==1.0.7
Django==3.2.4
django-cors-headers==3.7.0
django-extensions==2.2.3
django-filter==2.4.0
django-import-export==2.5.0
django-localflavor==2.2
django-phonenumber-field==3.0.1
django-rest-auth==0.9.5
django-simple-history==3.0.0
django-storages==1.8
djangorestframework==3.12.4
mysqlclient==2.0.3
phonenumbers==8.10.20
Pillow==8.2.0
requests==2.23.0
django-import-export==2.5.0
django-google-maps==0.12.4
drf-yasg==1.20.0
Flask==2.0.1
pandas==1.1.5
beautifulsoup4==4.9.3
slugify==0.0.1
django-taggit==1.3.0
PyMySQL==1.0.2
django-crontab==0.7.1
Werkzeug==2.0.2
numpy
python-dateutil==2.7.3
pytest==6.2.5
pytz==2019.3
jmespath==0.10.0
docutils==0.15.2
lxml==4.7.1
cffi==1.15.0
future==0.18.2
ipython==7.16.3
olefile==0.46
soupsieve==2.3.1
html5lib==1.1
httplib2==0.15.0
defusedxml==0.7.1
pip==21.3.1
keyring==18.0.1
PyYAML==5.3.1
Babel==2.9.1
botocore==1.13.50
s3transfer==0.2.1
MarkupSafe==2.0.1
Jinja2==3.0.3
click==8.0.3
blinker==1.4
itsdangerous==2.0.1
setuptools==45.2.0
sqlparse
asgiref==3.4.1
colorama==0.4.3
py==1.11.0
python-stdnum==1.17
tablib==3.1.0
xlrd==2.0.1
xlwt==1.3.0
MarkupPy==1.14
openpyxl==3.0.9
certifi==2019.11.28
chardet==3.0.4
itypes==1.2.0
coreapi==2.3.3
coreschema==0.0.4
uritemplate==4.1.1
cryptography==2.8
urllib3==1.25.8
simplejson==3.16.0
coverage==6.2
six==1.14.0
Pygments==2.10.0
inflection==0.5.1
idna==2.8
paramiko==2.6.0
pyparsing==3.0.6
google_api_python_client==2.42.0
oauth2client==4.1.3
ua-parser==0.10.0
user-agents==2.2.0
django-user-agents==0.4.0
django_db_logger
dataclasses==0.1
djongo==1.3.3
pymongo==3.11.2
djangotoolbox>=1.6.0
django-dbindexer>=1.6.0
gunicorn==19.9.0
django-crispy-forms==1.9.0
dnspython==1.16.0
For dealing with module named Djongo for connecting Django with MongoDb , one should be completely aware of the modules versions being used in the environment.
Make sure your using the library versions stated below.
asgiref==3.5.0,
Django==4.0.3,
djongo==1.3.6,
dnspython==2.2.1,
pykerberos==1.2.4,
pymongo==3.12.1,
python-snappy==0.6.1,
pytz==2022.1,
sqlparse==0.2.4,
configure the Database settings in the settings.py. Its not necessary to use host while connnecting to the localhost of MongoDb.
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'your-db-name',
}
}

django.db.utils.ProgrammingError: relation does not exist LINE 1

I encountered an issue while migrating a DB using django:
Traceback (most recent call last): File
"C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 84, in _execute
return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "myBlog_category" does not
exist LINE 1: ...g_category"."name", "myBlog_category"."name" FROM
"myBlog_ca...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last): File "manage.py", line 22, in
main() File "manage.py", line 18, in main
execute_from_command_line(sys.argv) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management_init_.py",
line 401, in execute_from_command_line
utility.execute() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management_init_.py",
line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py",
line 330, in run_from_argv
self.execute(*args, **cmd_options) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py",
line 368, in execute
self.check() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py",
line 392, in check
all_issues = checks.run_checks( File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py",
line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases) File
"C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py",
line 13, in check_url_config
return check_resolver(resolver) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py",
line 23, in check_resolver
return check_method() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py",
line 408, in check
for pattern in self.url_patterns: File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py",
line 48, in get
res = instance.dict[self.name] = self.func(instance) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py",
line 589, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File
"C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py",
line 48, in get
res = instance.dict[self.name] = self.func(instance) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py",
line 582, in urlconf_module
return import_module(self.urlconf_name) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\importlib_init_.py",
line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File
"", line 991, in _find_and_load File
"", line 975, in _find_and_load_unlocked
File "", line 671, in _load_unlocked
File "", line 783, in
exec_module File "", line 219, in
call_with_frames_removed File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\blog\urls.py", line 8, in
path('', include('myBlog.urls')), File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\conf.py",
line 34, in include
urlconf_module = import_module(urlconf_module) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\importlib_init.py",
line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File
"", line 991, in _find_and_load File
"", line 975, in _find_and_load_unlocked
File "", line 671, in _load_unlocked
File "", line 783, in
exec_module File "", line 219, in
_call_with_frames_removed File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\urls.py", line 2,
in
from .views import HomeView, ArticleDetailView, AddPostView, UpdatePostView, DeletePostView, AddCategoryView, CategoryView,
CategoryListView, LikeView, AddCommentView File
"C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\views.py", line 4,
in
from .forms import PostForm, EditForm, CommentForm File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\forms.py", line 6,
in
for item in choices: File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py",
line 287, in iter
self._fetch_all() File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py",
line 1303, in _fetch_all
self._result_cache = list(self._iterable_class(self)) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py",
line 142, in iter
return compiler.results_iter(tuple_expected=True, chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File
"C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py",
line 1108, in results_iter
results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size) File
"C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py",
line 1156, in execute_sql
cursor.execute(sql, params) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 98, in execute
return super().execute(sql, params) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\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\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 75, in _execute_with_wrappers
return executor(sql, params, many, context) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 84, in _execute
return self.cursor.execute(sql, params) File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py",
line 90, in exit
raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 84, in _execute
return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "myBlog_category" does not
exist LINE 1: ...g_category"."name", "myBlog_category"."name" FROM
"myBlog_ca...
I deployed the app to heroku and got errors so I tried to change the sqlite db to psql before commiting it to heroku but after doing this tutorial migrations did not work anymore, I got stuck on the 3rd step of the tutorial.
I tried the following:
Delete migrations folder from myBlog
Delete db.sqlite3 file
After removing the files/folders above I tried python manage.py makemigrations and got the following error:
Traceback (most recent call last):
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 84, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedTable: relation "myBlog_category" does not exist
LINE 1: ...g_category"."name", "myBlog_category"."name" FROM "myBlog_ca...
^
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 "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py",
line 401, in execute_from_command_line
utility.execute()
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management_init_.py",
line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py",
line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py",
line 368, in execute
self.check()
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py",
line 392, in check
all_issues = checks.run_checks(
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py",
line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py",
line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py",
line 23, in check_resolver
return check_method()
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py",
line 408, in check
for pattern in self.url_patterns:
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py",
line 48, in get
res = instance.dict[self.name] = self.func(instance)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py",
line 589, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py",
line 48, in get
res = instance.dict[self.name] = self.func(instance)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py",
line 582, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\importlib_init_.py",
line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 1014, in _gcd_import
File "", line 991, in _find_and_load
File "", line 975, in _find_and_load_unlocked
File "", line 671, in _load_unlocked
File "", line 783, in exec_module
File "", line 219, in call_with_frames_removed
File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\blog\urls.py", line 8, in
path('', include('myBlog.urls')),
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\conf.py",
line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\importlib_init.py",
line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 1014, in _gcd_import
File "", line 991, in _find_and_load
File "", line 975, in _find_and_load_unlocked
File "", line 671, in _load_unlocked
File "", line 783, in exec_module
File "", line 219, in _call_with_frames_removed
File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\urls.py", line 2,
in
from .views import HomeView, ArticleDetailView, AddPostView, UpdatePostView, DeletePostView, AddCategoryView, CategoryView,
CategoryListView, LikeView, AddCommentView
File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\views.py", line 4,
in
from .forms import PostForm, EditForm, CommentForm
File "C:\Users\rroct\Desktop\blog_Py_PostSQL\blog\myBlog\forms.py", line 6,
in
for item in choices:
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py",
line 287, in iter
self._fetch_all()
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py",
line 1303, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py",
line 142, in iter
return compiler.results_iter(tuple_expected=True, chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py",
line 1108, in results_iter
results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\sql\compiler.py",
line 1156, in execute_sql
cursor.execute(sql, params)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 98, in execute
return super().execute(sql, params)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\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\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 84, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py",
line 90, in exit
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\rroct\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py",
line 84, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "myBlog_category" does not exist
LINE 1: ...g_category"."name", "myBlog_category"."name" FROM "myBlog_ca...
Trying to run the server locally now, doesn't work.
While deploying it to heroku I got ProgrammingError - something close to what I get now. I tried to run:
heroku run python manage.py migrate
But got the app would return me the same error as the same traceback at the begging of the post.
My settings.py file:
"""
Django settings for blog project.
Generated by 'django-admin startproject' using Django 3.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
import django_heroku
import dj_database_url
from decouple import config
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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-97gr5qi*888x%%n!=yp(uf*xz!8(jucnfd!ln+_zkyg#8#e5th'
# 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',
'myBlog',
'members',
'ckeditor',
]
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 = 'blog.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 = 'blog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE' : 'django.db.backends.postgresql_psycopg2',
'NAME' : 'my_db',
'USER' : 'hero',
'PASSWORD' : 'my_db # 123',
'HOST' : 'localhost',
'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/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# 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 = 'home'
LOGOUT_REDIRECT_URL = 'home'
django_heroku.settings(locals())
For any other additional required informations please let me know.
Edit 1:
My models.py
from ckeditor.fields import RichTextField
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
class Category(models.Model):
name = models.CharField(max_length=255)
def __str__(self) :
return self.name
def get_absolute_url(self) :
return reverse('home')
class Profile(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
bio = models.TextField()
profile_pic = models.ImageField(null=True, blank=True, upload_to="images/profile")
website_url = models.CharField(max_length=255, null=True, blank=True)
facebook_url = models.CharField(max_length=255, null=True, blank=True)
instagram_url = models.CharField(max_length=255, null=True, blank=True)
twitter_url = models.CharField(max_length=255, null=True, blank=True)
pinterest_url = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return str(self.user)
def get_absolute_url(self) :
return reverse('home')
class Post(models.Model):
title = models.CharField(max_length=255)
header_image = models.ImageField(null=True, blank=True, upload_to="images/")
title_tag = models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = RichTextField(blank=True, null=True)
post_date = models.DateField(auto_now_add=True)
category = models.CharField(max_length=255, default='uncategorized')
snippet = models.CharField(max_length=255)
likes = models.ManyToManyField(User, related_name='blog_posts')
def total_likes(self):
return self.likes.count()
def __str__(self):
return self.title + ' | ' + str(self.author)
# Create your models here.
def get_absolute_url(self):
return reverse('article-detail', args=(str(self.id),))
class Comment(models.Model):
post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
name = models.CharField(max_length=255)
body = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.post.title, self.name)
views.py for myBlog app:
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post, Category, Comment
from .forms import PostForm, EditForm, CommentForm
from django.urls import reverse_lazy, reverse
from django.http import HttpResponseRedirect
from django.core.paginator import Paginator
# Create your views here.
def LikeView(request, pk):
post = Post.objects.get(id=pk)
liked = False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
liked = False
else:
post.likes.add(request.user)
liked = True
return HttpResponseRedirect(reverse('article-detail', args=[str(pk)]))
class HomeView(ListView):
model = Post
template_name = 'home.html'
ordering = ['-post_date']
def get_context_data(self, *args, **kwargs):
cat_menu = Category.objects.all()
context = super(HomeView, self).get_context_data(*args, **kwargs)
context["cat_menu"] = cat_menu
return context
class ArticleDetailView(DetailView):
model = Post
template_name = 'article_details.html'
def get_context_data(self, *args, **kwargs):
cat_menu = Category.objects.all()
context = super(ArticleDetailView, self).get_context_data(*args, **kwargs)
stuff = get_object_or_404(Post, id=self.kwargs['pk'])
liked = False
if stuff.likes.filter(id=self.request.user.id).exists():
liked = True
total_likes = stuff.total_likes()
context["cat_menu"] = cat_menu
context["total_likes"] = total_likes
context["liked"] = liked
return context
class AddPostView(CreateView):
model = Post
form_class = PostForm
template_name = 'add_post.html'
def CategoryListView(request):
cat_menu_list = Category.objects.all()
return render(request, 'category_list.html', {'cat_menu_list': cat_menu_list})
def CategoryView(request, cats):
category_posts = Post.objects.filter(category=cats.title().replace('-', ' '))
return render(request, 'categories.html', {'cats': cats.title().replace('-', ' '), 'category_posts': category_posts})
class AddCategoryView(CreateView):
model = Category
fields = '__all__'
template_name = 'add_category.html'
class UpdatePostView(UpdateView):
model = Post
template_name = 'update_post.html'
form_class = EditForm
class DeletePostView(DeleteView):
model = Post
template_name = 'delete_post.html'
success_url = reverse_lazy('home')
class AddCommentView(CreateView):
model = Comment
form_class = CommentForm
template_name = 'add_comment.html'
def form_valid(self, form):
form.instance.post_id = self.kwargs['pk']
return super().form_valid(form)
success_url = reverse_lazy('home')
You shouldn't have deleted the migrations folder. Add this folder to your application and add the init file to it. Then create migrations locally. You have to create migrations locally. Heroku should not (and will not) create migration files. Heroku is just executing your code.
Also, if the data in the database is not important, you can re-create db to update the migration table. Or you can update it manually.
Steps
1. Creating a migration folder
cd ./your_app
mkdir migrations
cd migrations
touch __ini__.py
2. Creating migrations
./manage.py makemigrations
3. Pushing on heroku
4. Applying migrations
heroku run python manage.py migrate
P.S: I think Heroku has the tools to manage the Django app. Please refer to the documentation. I think applying migrations should be automatic.
You should performing steps 1-3 locally.
You can re-create the database on heroku or reset it. If you are re-creating the database, do not forget to change the access parameters in the project settings

Django migration error : return self.cursor.execute(sql, params) django.db.utils.ProgrammingError:

I tried to delete the migrations folder and db.sqlite3 as suggestions but it didn't work. I've also tried to downgrade version of django. Please look at the error below, I think it's the problem with database :
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\core\management\__init__.py", line 357, in execute
django.setup()
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\apps\registry.py", line 112, in populate
app_config.import_models()
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "c:\python38\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\Admin\Downloads\store2\Django-E-Commerce-master\user\models.py", line 8, in <module>
from home.models import Language
File "C:\Users\Admin\Downloads\store2\Django-E-Commerce-master\home\models.py", line 21, in <module>
for rs in llist:
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\models\query.py", line 268, in __iter__
self._fetch_all()
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\models\query.py", line 1186, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\models\query.py", line 54, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\models\sql\compiler.py", line 1065, in execute_sql
cursor.execute(sql, params)
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\backends\utils.py", line 100, in execute
return super().execute(sql, params)
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\backends\utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\Admin\Downloads\store2\env2\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "home_language" does not exist
LINE 1: ...ge"."create_at", "home_language"."update_at" FROM "home_lang...
This is setting file,
import os
from django.utils.translation import gettext_lazy as _
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '!l3!x0w-(f39+(#*a3a^8p#gf+o66e(#c#w1u13u*0=#-qpxbn'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'user.apps.UserConfig',
'order.apps.OrderConfig',
'product.apps.ProductConfig',
'home.apps.HomeConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ckeditor',
'mptt',
'currencies',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.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',
'currencies.context_processors.currencies'
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.0/topics/i18n/
LANGUAGES = [
('en', _('English')),
('tr', _('Turkish')),
]
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
DEFAULT_CURRENCY = 'USD'
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.0/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
# ...
SITE_ID = 1
####################################
## CKEDITOR CONFIGURATION ##
####################################
CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js'
CKEDITOR_UPLOAD_PATH = 'images/'
CKEDITOR_IMAGE_BACKEND = "pillow"
CKEDITOR_CONFIGS = {
'default': {
'toolbar': None,
},
}
###################################
#APPEND_SLASH=False
This is the model part where it is printing out the error :
class Language(models.Model):
name= models.CharField(max_length=20)
code= models.CharField(max_length=5)
status=models.BooleanField()
create_at=models.DateTimeField(auto_now_add=True)
update_at=models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
llist = Language.objects.filter(status=True)
list1 = []
for rs in llist:
list1.append((rs.code,rs.name))
langlist = (list1)
I think there's something wrong with this part of model.py since it throws out same error when I delete everything and leave only this part in models.py
I think the cause is this line llist = Language.objects.filter(status=True)

Django 'runserver' command is producing an error

the following error is produced when I use the 'runserver' command:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 60, in execute
super().execute(*args, **options)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute
output = self.handle(*args, **options)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 67, in handle
if not settings.DEBUG and not settings.ALLOWED_HOSTS:
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__
self._setup(name)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 66, in _setup
self._wrapped = Settings(settings_module)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 157, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'blog'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 336, in run_from_argv
connections.close_all()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/utils.py", line 219, in close_all
for alias in self:
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/utils.py", line 213, in __iter__
return iter(self.databases)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/utils.py", line 147, in databases
self._databases = settings.DATABASES
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__
self._setup(name)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 66, in _setup
self._wrapped = Settings(settings_module)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 157, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'blog'
Here is my manage.py file:
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Blog.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
here is my wsgi file:
"""
WSGI config for Blog project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Blog.settings')
application = get_wsgi_application()
Here is my settings.py:
"""
Django settings for Blog project.
Generated by 'django-admin startproject' using Django 2.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '1mk9ghpc7tg!%1k)#sc*q^o3h&^x=c*pfqa=4-+l*sl)oi#mhx'
# 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',
]
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 = 'Blog.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 = 'Blog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.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/2.2/howto/static-files/
STATIC_URL = '/static/'
I have tried doing a lot of things which I found here but none gave me the desired result. Also, the errors which the questions had were not the same as this one. I also looked at a lot of posts online and still couldn't find the answer.
Please see this and I would be highly obliged if I could receive an answer.
i think you forgot to add application name in installed apps list in settings.py
You have not installed blog in INSTALLED_APPS.
You need to change INSTALLED_APPS to something like this:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog.apps.BlogConfig'
]
This is not related to your specific question, but just good advice if you keep posting on Stack Overflow. NEVER share your secret key, which you just did when you posted your settings.py.
Do you have any app called Blog? I hope you have forgotten to add it to the INSTALLED_APPS