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',
}
}
Related
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
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.
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)
I just finished to setup my website with django, so I tryed to login on my /admin page but the server return "500 server error", I cannot manage my db now.
There isn't error on apache log, this is what browser console say:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
http://www.example.com/admin/login/?next=/admin/
I think that this part of url is really strange, I'm not sure:
/admin/login/?next=/admin/
This is my urls.py file:
from django.conf.urls import url
from django.contrib import admin
from Gestione import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.index),
url(r'^faq', views.faq),
url(r'^contacts', views.contacts),
]
I'm on ubuntu server 15.04 with apache 2.4.10 and django 1.9.6
Thanks for help
EDIT: settings.py
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/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*********'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['www.example.com','example.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Gestione',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'proj.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 = 'proj.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'gestione.db'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/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/1.9/topics/i18n/
LANGUAGE_CODE = 'en-EN'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'Gestione/static')
EDIT 2 (django traceback):
Traceback:
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/sqlite3/base.py" in execute
323. return Database.Cursor.execute(self, query, params)
The above exception (unable to open database file) was the direct cause of the following exception:
File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.4/dist-packages/django/contrib/admin/options.py" in wrapper
541. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/django/contrib/admin/sites.py" in inner
244. return view(request, *args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/django/contrib/admin/options.py" in change_view
1440. return self.changeform_view(request, object_id, form_url, extra_context)
File "/usr/local/lib/python3.4/dist-packages/django/utils/decorators.py" in _wrapper
67. return bound_func(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/django/utils/decorators.py" in bound_func
63. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/usr/lib/python3.4/contextlib.py" in inner
30. return func(*args, **kwds)
File "/usr/local/lib/python3.4/dist-packages/django/contrib/admin/options.py" in changeform_view
1378. self.save_model(request, new_object, form, not add)
File "/usr/local/lib/python3.4/dist-packages/django/contrib/admin/options.py" in save_model
991. obj.save()
File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py" in save
708. force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py" in save_base
736. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py" in _save_table
801. forced_update)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py" in _do_update
851. return filtered._update(values) > 0
File "/usr/local/lib/python3.4/dist-packages/django/db/models/query.py" in _update
645. return query.get_compiler(self.db).execute_sql(CURSOR)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/sql/compiler.py" in execute_sql
1149. cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
File "/usr/local/lib/python3.4/dist-packages/django/db/models/sql/compiler.py" in execute_sql
848. cursor.execute(sql, params)
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py" in execute
79. return super(CursorDebugWrapper, self).execute(sql, params)
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.4/dist-packages/django/db/utils.py" in __exit__
95. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/local/lib/python3.4/dist-packages/django/utils/six.py" in reraise
685. raise value.with_traceback(tb)
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py" in execute
64. return self.cursor.execute(sql, params)
File "/usr/local/lib/python3.4/dist-packages/django/db/backends/sqlite3/base.py" in execute
323. return Database.Cursor.execute(self, query, params)
Exception Type: OperationalError at /admin/Gestione/game/5/change/
Exception Value: unable to open database file
You should post your settings.py file here, remember to remove any sensitive variables. I suspect that you're getting an error because DEBUG = False and ALLOWED_HOSTS = [].
Try (temporarily) setting ALLOWED_HOSTS = ['*']
Following the MongoDB tutorial (http://django-mongodb-engine.readthedocs.org/en/latest/tutorial.html), I have a model called Post in an app called 'tutorial.' I have the app, along with djangotoolbox, installed:
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'djangotoolbox',
'tutorial'
)
I have the following connection settings with a name, user, and password that is set up on MongoLab:
DATABASES = {
'default': {
'ENGINE': 'django_mongodb_engine',
'NAME': '*****',
'USER': '*****',
'PASSWORD': '******',
'HOST': 'ds047720.mongolab.com',
'PORT': '47720'
}
}
When I SSH into my host, I can run manage.py validate and I get "0 errors found." When I go into the shell and follow the tutorial to create a new Post, this is what happens:
(InteractiveConsole)
>>> from tutorial.models import Post
>>> post = Post.objects.create(
... title='123',
... text='test',
... tags=['a','b']
... )
Traceback (most recent call last):
File "<console>", line 4, in <module>
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django/db/models/manager.py", line 149, in create
return self.get_query_set().create(**kwargs)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django/db/models/query.py", line 416, in create
obj.save(force_insert=True, using=self.db)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django/db/models/base.py", line 548, in save
force_update=force_update, update_fields=update_fields)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django/db/models/base.py", line 668, in save_base
result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django/db/models/manager.py", line 215, in _insert
return insert_query(self.model, objs, fields, **kwargs)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django/db/models/query.py", line 1675, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/djangotoolbox/db/basecompiler.py", line 592, in execute_sql
key = self.insert(to_insert, return_id=return_id)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django_mongodb_engine/compiler.py", line 84, in wrapper
return func(*args, **kwargs)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django_mongodb_engine/compiler.py", line 387, in insert
collection = self.get_collection()
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django_mongodb_engine/compiler.py", line 296, in get_collection
return self.connection.get_collection(self.query.get_meta().db_table)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django_mongodb_engine/base.py", line 196, in get_collection
collection = self.collection_class(self.database, name, **kwargs)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django_mongodb_engine/base.py", line 204, in __getattr__
self._connect()
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/django_mongodb_engine/base.py", line 261, in _connect
self.connection = connection_class(**conn_options)
File "/home1/kevinlak/tabenv/lib/python2.7/site-packages/pymongo/mongo_client.py", line 369, in __init__
raise ConnectionFailure(str(e))
DatabaseError: timed out
>>>
Obviously, Django is having a difficult time connecting to the database, but I'm able to connect just fine using Mongo Management Studio. I've read similar tutorials here: http://compsocsci.blogspot.com/2012/02/getting-started-with-django-heroku-and.html
and here:
http://dennisgurnick.com/2010/07/06/bootstrapping-a-django-with-mongo-project/
but I have no idea what's stopping django from connecting to my database. Has anyone overcome a similar issue with the mongodb engine? Does anyone know what I'm missing?