I am working on a Linux server that is hosted on Amazon's server and I have completely set up the server. The final thing I am trying to do is host one of my old projects that I created on the server which is in the Flask framework.
I am trying to run the Python file that sets up my database that is required to run my project.
I am using a virtual machine inside the server that will run my project and every time I run the command I get the following error:
(venv) grader#ip-10-20-6-95:/var/www/catalog/catalog$ python setup_database.py
Traceback (most recent call last):
File "setup_database.py", line 63, in <module>
Base.metadata.create_all(engine)
File "/var/www/catalog/venv/local/lib/python2.7/site-packages/sqlalchemy/schema.py", line 2848, in create_all
tables=tables)
File "/var/www/catalog/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1479, in _run_visitor
conn._run_visitor(visitorcallable, element, **kwargs)
File "/var/www/catalog/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1122, in _run_visitor
**kwargs).traverse_single(element)
File "/var/www/catalog/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/visitors.py", line 122, in traverse_single
return meth(obj, **kw)
File "/var/www/catalog/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/ddl.py", line 70, in visit_metadata
self.traverse_single(table, create_ok=True)
File "/var/www/catalog/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/visitors.py", line 122, in traverse_single
return meth(obj, **kw)
File "/var/www/catalog/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/ddl.py", line 89, in visit_table
self.connection.execute(schema.CreateTable(table))
File "/var/www/catalog/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 662, in execute
params)
File "/var/www/catalog/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 720, in _execute_ddl
compiled
File "/var/www/catalog/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 874, in _execute_context
context)
File "/var/www/catalog/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1024, in _handle_dbapi_exception
exc_info
File "/var/www/catalog/venv/local/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 196, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb)
File "/var/www/catalog/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 867, in _execute_context
context)
File "/var/www/catalog/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 324, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (ProgrammingError) no schema has been selected to create in
'\nCREATE TABLE users (\n\tid SERIAL NOT NULL, \n\tusername VARCHAR(100), \n\temail VARCHAR(225) NOT NULL, \n\tprofile_pic VARCHAR(225) NOT NULL, \n\tPRIMARY KEY (id)\n)\n\n' {}
I am not sure why I get this error.
The commands I ran to set up PostgreSQL (if that should matter):
$ sudo apt-get install libpq-dev python-dev
$ sudo apt-get install postgresql postgresql-contrib
$ sudo su - postgres
$ psql
# CREATE USER catalog WITH PASSWORD 'sillypassword';
# ALTER USER catalog CREATEDB;
# CREATE DATABASE catalog WITH OWNER catalog;
# \c catalog
# REVOKE ALL ON SCHEMA public FROM public;
# GRANT ALL ON SCHEMA public TO catalog;
# \q
$ exit
How could I fix this problem?
no schema has been selected to create in
You get this error when your search_path setting has no valid first entry (typically empty). Postgres does not know in which schema to create the table.
Fix your search_path setting, or schema-qualify object names (like: public.users). But fix your search_path in any case.
Details:
How does the search_path influence identifier resolution and the "current schema"
This issue was answered already: https://dba.stackexchange.com/a/275116/114247
The fix is:
grant usage on schema public to public;
grant create on schema public to public;
I found the file created by pg_dump (under postgres 10.7) had
SELECT pg_catalog.set_config('search_path', '', false);
near the top of it. So when importing the file, it manipulated the search path, which persisted throughout the current session.
Commenting that line out (and starting a new session) fixed the problem.
You do not have a schema created. Create a schema using CREATE SCHEMA public;
then you can execute grant usage on schema public to public; and grant create on schema public to public
I was stuck across same problem and after doing a lot of research, I got the below solution, assuming you are using flask models to create database using sqlalchemy:
while creating models use the below command before defining columns of models:
__table_args__ = {"schema":"schema_name"}
Hope this helps you out.
Related
An issue occurred where our production database was not getting migrated due to an error during migration. This error involved the usage of the package django-tenants, which is a fork of the django-tenant-schemas package.
The error:
Traceback (most recent call last):
File "/backend/manage.py", line 21, in <module>
main()
File "/backend/manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.9/site-packages/django_tenants/management/commands/migrate_schemas.py", line 89, in handle
executor.run_migrations(tenants=tenants)
File "/usr/local/lib/python3.9/site-packages/django_tenants/migration_executors/standard.py", line 14, in run_migrations
Starting new HTTPS connection (1): o1380729.ingest.sentry.io:443
run_migrations(self.args, self.options, self.codename, schema_name, idx=idx, count=len(tenants))
File "/usr/local/lib/python3.9/site-packages/django_tenants/migration_executors/base.py", line 45, in run_migrations
migration_recorder.ensure_schema()
File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 70, in ensure_schema
raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc)
django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (relation "django_migrations" already exists
)
What could cause this error?
The fact that several tenants did migrate before the error occurred tells you that the error is caused by a specific tenant. To find where the error is coming from we need to follow the traceback. On the second to last line we see:
File "/usr/local/lib/python3.9/site-packages/django_tenants/migration_executors/standard.py", line 14, in run_migrations
Starting new HTTPS connection (1): o1380729.ingest.sentry.io:443 run_migrations(self.args, self.options, self.codename, schema_name, idx=idx, count=len(tenants))
File "/usr/local/lib/python3.9/site-packages/django_tenants/migration_executors/base.py", line 45, in run_migrations migration_recorder.ensure_schema()
File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py"
So looking into the django_tenants source code near line 45 of /usr/local/lib/python3.9/site-packages/django_tenants/migration_executors/base.py we see this code:
connection = connections[options.get('database', get_tenant_database_alias())]
connection.set_schema(schema_name, tenant_type=tenant_type)
# ensure that django_migrations table is created in the schema before migrations run, otherwise the migration
# table in the public schema gets picked and no migrations are applied
migration_recorder = MigrationRecorder(connection)
migration_recorder.ensure_schema() # line 45
Since the schema_name is passed to connection.set_schema(schema_name, tenant_type=tenant_type) we can go up one line and put a print statement to print the name of the schema being migrated. This print statement will show on the console during migrations and show the schema which has the issue. In our case, it was cause by duplicate schema names being allowed because of different capitalization in the schema names.
To change the schema names we went into the Django shell using python manage.py shell, imported the tenant model, called instance = TenantModel.objects.get(schema_name="conflicting_name") and set the schema to a different name using instance.schema_name("new_name") and called instance.save() on the instance.
This ran a migration and fixed the issue!
I am pretty new in Django and Python and I am trying to follow this videotutorial about how to migrate a Django application from SqlLite to Postgres database:
https://www.youtube.com/watch?v=ZgRkGfoy2nE&t=554s
But I am finding some problem. Following the details on what I have done:
I am working on Ubuntu 20.04 and I have a Django application made by someone else that uses SQLLite and that have to be migrated on Postgres. Following the previous tutorial I have done the following steps:
First of all I installed Postegres and PgAdmin4 on my Ubuntu system. Then here I created a DB named dgsrgdb that have to be my new database for my application in replacement of SQL Lite DB.
I installed this package to let Python\Django operate with Postgres:
pip3 install psycopg2-binary
I performed the backup of my original SqlLite DB by this command:
python3 manage.py dumpdata > datadump.json
and I obtained the datadump.json file that should contains the data inside the original DB that have to moved on the new Postgres DB.
Into the Django settings.py file I replaced this configuration:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
whith this configuration related to Postgres:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dgsrg',
'USER': 'dgsrguser',
'PASSWORD': 'password',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
so now my application points to my new dgsrgdb previously created on Postgres. I am using the "root" postgres user at the moment.
And now my problem. As shown in the tutorial I execute this command in my command line in order to create my tables on my dgsrg Postgres DB:
python3 manage.py migrate --run-syncdb
The tables related to my Django applications seems to be created on my new DB, this is what I have using PgAdmin:
Then following the tutorial I am trying to import the data previously exported into my datadump.json* file into these tables using this command:
python manage.py loaddata datadump.json
but perfroming this command I am obtaining this error message:
(DGSRG) andrea#ubuntu:~/Documenti/Python-WS/django_projects/dgsrg$ python manage.py loaddata datadump.json
Traceback (most recent call last):
File "/home/andrea/Documenti/Python-WS/Environments/DGSRG/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "django_content_type_app_label_model_76bd3d3b_uniq"
DETAIL: Key (app_label, model)=(admin, logentry) already exists.
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 "/home/andrea/Documenti/Python-WS/Environments/DGSRG/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/home/andrea/Documenti/Python-WS/Environments/DGSRG/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/andrea/Documenti/Python-WS/Environments/DGSRG/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/andrea/Documenti/Python-WS/Environments/DGSRG/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute
output = self.handle(*args, **options)
File "/home/andrea/Documenti/Python-WS/Environments/DGSRG/lib/python3.8/site-packages/django/core/management/commands/loaddata.py", line 72, in handle
self.loaddata(fixture_labels)
File "/home/andrea/Documenti/Python-WS/Environments/DGSRG/lib/python3.8/site-packages/django/core/management/commands/loaddata.py", line 114, in loaddata
self.load_label(fixture_label)
File "/home/andrea/Documenti/Python-WS/Environments/DGSRG/lib/python3.8/site-packages/django/core/management/commands/loaddata.py", line 181, in load_label
obj.save(using=self.using)
File "/home/andrea/Documenti/Python-WS/Environments/DGSRG/lib/python3.8/site-packages/django/core/serializers/base.py", line 223, in save
models.Model.save_base(self.object, using=using, raw=True, **kwargs)
File "/home/andrea/Documenti/Python-WS/Environments/DGSRG/lib/python3.8/site-packages/django/db/models/base.py", line 790, in save_base
updated = self._save_table(
File "/home/andrea/Documenti/Python-WS/Environments/DGSRG/lib/python3.8/site-packages/django/db/models/base.py", line 872, in _save_table
updated = self._do_update(base_qs, using, pk_val, values, update_fields,
File "/home/andrea/Documenti/Python-WS/Environments/DGSRG/lib/python3.8/site-packages/django/db/models/base.py", line 926, in _do_update
return filtered._update(values) > 0
File "/home/andrea/Documenti/Python-WS/Environments/DGSRG/lib/python3.8/site-packages/django/db/models/query.py", line 803, in _update
return query.get_compiler(self.db).execute_sql(CURSOR)
File "/home/andrea/Documenti/Python-WS/Environments/DGSRG/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1522, in execute_sql
cursor = super().execute_sql(result_type)
File "/home/andrea/Documenti/Python-WS/Environments/DGSRG/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1156, in execute_sql
cursor.execute(sql, params)
File "/home/andrea/Documenti/Python-WS/Environments/DGSRG/lib/python3.8/site-packages/django/db/backends/utils.py", line 98, in execute
return super().execute(sql, params)
File "/home/andrea/Documenti/Python-WS/Environments/DGSRG/lib/python3.8/site-packages/django/db/backends/utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/andrea/Documenti/Python-WS/Environments/DGSRG/lib/python3.8/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/andrea/Documenti/Python-WS/Environments/DGSRG/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "/home/andrea/Documenti/Python-WS/Environments/DGSRG/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/andrea/Documenti/Python-WS/Environments/DGSRG/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: Problem installing fixture '/home/andrea/Documenti/Python-WS/django_projects/dgsrg/datadump.json': Could not load contenttypes.ContentType(pk=1): duplicate key value violates unique constraint "django_content_type_app_label_model_76bd3d3b_uniq"
DETAIL: Key (app_label, model)=(admin, logentry) already exists.
Why? What could be the problem? What am I missing? How can I try to fix it?
Before loading data using loaddata command,
We have to flush all the tables because django itself create some objects during migration.
Try running below command, command will flush data of all tables:
python manage.py sqlflush | python manage.py dbshell
Then, loaddata into the PostgreSQl.
The problem is that by dumping all the data from sqlite, you're also copying contenttypes. Keep in mind that the contenttypes framework contains metadata about your models. Your traceback error points to this possibility when you tried to load admin.LogEntry into the contenttypes table when it already had that data from migrate.
What you should do is to exclude contenttypes in your dumpdata.
python manage.py dumpdata --exclude=contenttypes
There is also a possibility that you may have to exclude auth.Permission since the default view, change, and delete permissions of models are created on migrate, though I cannot say whether this behavior happens during a run-syncdb. You could test dumpdata first without excluding auth.Permission.
I am not very sure why the error came but, I kind of solved it by specifying all app names needed in the dumped
python manage.py dumpdata auth.user auth.group app1 app2 app3 > database.json
it will dump all needed data and python manage.py loaddata database.json command won't return any error.
I'm developing a new django project and stuck with migration.
I would like to make a UserModel, and in order to do that, I did two things so far.
1. I made AuthUser model and set a Meta class in the class below.
In models.py
class AuthUser(AbstractUser):
user_type_id = models.PositiveIntegerField(choices=UserTypes.choices())
user_id = models.PositiveIntegerField()
class Meta(AbstractUser.Meta):
swappable = 'AUTH_USER_MODEL'
#property
def user_type(self):
return UserTypes(self.user_type_id)
def original_orm(self):
if self.user_type.value == UserTypes.raijosha.value:
return RaijoshaUsers.objects.filter(id=self.user_id).first()
elif self.user_type.value == UserTypes.shuttennsha.value:
return Users.objects.filter(id=self.user_id).first()
In settings.py, I set AUTH_USER_MODEL.
AUTH_USER_MODEL = 'recommend.AuthUser'
Here's the error codes.
Operations to perform:
Apply all migrations: admin, auth, contenttypes, recommend, recommend_raijousha, sessions
Traceback (most recent call last):
File "manage.py", line 25, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 355, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.6/dist-packages/django/core/management/commands/migrate.py", line 164, in handle
pre_migrate_apps = pre_migrate_state.apps
File "/usr/local/lib/python3.6/dist-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/state.py", line 218, in apps
return StateApps(self.real_apps, self.models)
File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/state.py", line 295, in __init__
raise ValueError("\n".join(error.msg for error in errors))
ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'recommend.authuser', but app 'recommend' doesn't provide model 'authuser'.
Could you please help us or give me an advise.
Applying admin.0001_initial...Traceback (most recent call last):
File "manage.py", line 25, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 355, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.6/dist-packages/django/core/management/commands/migrate.py", line 204, in handle
fake_initial=fake_initial,
File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/executor.py", line 115, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/operations/models.py", line 97, in database_forwards
schema_editor.create_model(model)
File "/usr/local/lib/python3.6/dist-packages/django/db/backends/base/schema.py", line 254, in create_model
definition, extra_params = self.column_sql(model, field)
File "/usr/local/lib/python3.6/dist-packages/django/db/backends/base/schema.py", line 144, in column_sql
db_params = field.db_parameters(connection=self.connection)
File "/usr/local/lib/python3.6/dist-packages/django/db/models/fields/related.py", line 994, in db_parameters
return {"type": self.db_type(connection), "check": self.db_check(connection)}
File "/usr/local/lib/python3.6/dist-packages/django/db/models/fields/related.py", line 991, in db_type
return self.target_field.rel_db_type(connection=connection)
File "/usr/local/lib/python3.6/dist-packages/django/db/models/fields/related.py", line 909, in target_field
return self.foreign_related_fields[0]
File "/usr/local/lib/python3.6/dist-packages/django/db/models/fields/related.py", line 653, in foreign_related_fields
return tuple(rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field)
File "/usr/local/lib/python3.6/dist-packages/django/db/models/fields/related.py", line 640, in related_fields
self._related_fields = self.resolve_related_fields()
File "/usr/local/lib/python3.6/dist-packages/django/db/models/fields/related.py", line 625, in resolve_related_fields
raise ValueError('Related model %r cannot be resolved' % self.remote_field.model)
ValueError: Related model 'recommend.authuser' cannot be resolved
Considering an advise, I did delete migration files.
But another error occured shown above.
It happens if you ran default auth app migrations and later changed the AUTH_USER_MODEL in settings.py. You can try following:
# comment AUTH_USER_MODEL in settings.py so it points to default User model
python manage.py migrate auth zero
# uncomment to be AUTH_USER_MODEL='recommend.AuthUser'
python manage.py migrate auth
I delete all the migration files and database and applied it.
Then I could migrate.
Note : I am using sqlite3 as a database.
Hi,
I easily solved it by deleting all the migration files in the migrations folder except the __init__.py file. And also delete db.sqlite3. Now run the following commands : python manage.py makemigrations and then python manage.py migrate. Now you'll have to create the super user once again, so for this just type the following commmand : python manage.py createsuperuser. Then it will prompt for username, email and password, so enter your credentials and all will continue to work properly once again I hope that this will be helpful.
Click Here To View Image
For me helped split on two migration
create new table (with out connection betwin new and old tables and without AUTH_USER_MODEL = 'recommend.authuser')
add AUTH_USER_MODEL to settins.py and other connections with new table
I had to refer to this stack: to be able to solve that issue.
I simply followed the steps bellow:
Since I am not using sqlite, I made new database configuration that refers to my postgres, in my settings.py:
old database i am not more going to use:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'leszexpert', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '5432', } }
new database I want to start using:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'leszexpert_db', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '5432', } }
As you can see, the difference is the DATABASE NAME (referenced after ENGINE)!!!!!!
I stopped the server and already previously deleted all existing corresponding migrations.
I closed my IDE VScode (I have realised from experience that when something does not take effect, after closing it and reopening it, it most time ends up taking effect)
when I reopened the code editor, I uncomment my models (i commented them previously), then VERY VERY IMPORTANT: DO NOT START OR RUN YOUR SERVER AT THIS POINT. because now you are about to operate on the new database specified above and the issue as you know we are trying to solve is that if you run migration of that type of models after runing the server, it will not create your model...therefore DO NOT RUN SERVER YET
INSTEAD DO THIS: RUN MIGRATIONS AND THEN MIGRATE
ET VOILA (French expression to That is it): your extended user model will be created in your database:
Thank you for reading my answer
I'm using MySQL.
The solution, for me, was to delete the files inside migrations folder (all but __ init__.py), DROP and CREATE database in MySQL Workbench and run python manage.py makemigrations and python manage.py migrate again.
Therefore, I had to create a new superuser and all my data was lost :(
If you are still in development and can take the pain of filling out the db data again then here's what all you need to know!.
you need to first delete all the files related with db(including sqlite.py if it exists), you can do this by the help of below following ways.
find . -path "/migrations/.py" -not -name "init.py" -delete
find . -path "/migrations/.pyc" -delete
Now either delete the entire data,tables of your DB or just Drop the db and make a new one and do the migrations separately for each app and migrate it.
python manage.py makemigrations appname
python manage.py migrate appname
then if you get any error for the session like "ProgrammingError: relation "django_session" does not exist"
then follow these steps below:
python manage.py migrate --fake sessions zero
then your sessions migrate will be
python manage.py showmigrations
sessions
[ ] 0001_initial
then migrate with --fake-initial again
python manage.py migrate --fake-initial
now do try to the runserver again and the problem must have been by gone now, if not then please let me know,I'll try my best possible way to solve it.
Thanks for looking at this.
If your migration works locally and not on server do this for server;
root#abcomp:~/var/www/yourapp$sudo -u postgres psql
#list your databases
postgres=#\l
postgres=#\c your_dbname;
your_db=# delete from django_migrations;
# after pulling the latest working changes
(venv)root#abcomp/var/www/yourapp$./manage.py migrate --fake
I am trying to add One-to-One keys into my Django app, but I always get that error when I try to "migrate" process (makemigrations works great).
Applying xyzapp.0007_personne_extended_foreign...Traceback (most recent call last):
File "manage.py", line 29, in <module>
execute_from_command_line(sys.argv)
File "/opt/xyz/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
utility.execute()
File "/opt/xyz/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 346, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/opt/xyz/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 394, in run_from_argv
self.execute(*args, **cmd_options)
File "/opt/xyz/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 445, in execute
output = self.handle(*args, **options)
File "/opt/xyz/env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 222, in handle
executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
File "/opt/xyz/env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 110, in migrate
self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial)
File "/opt/xyz/env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 148, in apply_migration
state = migration.apply(state, schema_editor)
File "/opt/xyz/env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 91, in __exit__
self.execute(sql)
File "/opt/xyz/env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 111, in execute
cursor.execute(sql, params)
File "/opt/xyz/env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/opt/xyz/env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/opt/xyz/env/local/lib/python2.7/site-packages/django/db/utils.py", line 98, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/opt/xyz/env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/opt/xyz/env/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 124, in execute
return self.cursor.execute(query, args)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 226, in execute
self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorvalue
django.db.utils.OperationalError: (1005, 'Can\'t create table `xyz`.`#sql-600_297` (errno: 150 "Foreign key constraint is incorrectly formed")')
That's what my models looks like :
class PersonVolunteer(models.Model):
person = models.OneToOneField(Person)
class Person(models.Model):
name = models.CharField(max_length=100)
And the migration process that cause the crash :
class Migration(migrations.Migration):
dependencies = [
('xyzapp', '0014_member_to_person'),
]
operations = [
migrations.CreateModel(
name='PersonVolunteer',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('personne', models.OneToOneField(to='xyzapp.Personne')),
],
),
]
However, all works correctly when I test it even after the migrate error. But if that error message appears during "migrate", that should not be something good happening. If there's no problem, it is possible to skip that last step which crash my migration ?
Can someone can say me why do I get that error message and how I can resolve it ?
Thank you very much and have a great day !
I have found a solution, may be not the cleaner, but god dammit it works, that's perfect for me.
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cvmapp', '0006_person_extended'),
]
operations = [
migrations.AddField(
model_name='PersonVolunteer',
name='personne',
field=models.OneToOneField(related_name='info_volunteer', to='cvmapp.Person', db_constraint=False),
),
]
The trick was to add "db_constraint=False" as a parameter of the OneToOne field.
Please make sure all your MySQL tables are using the same storage engine (i.e. MyISM v. InnoDB). Especially tables that have ForeignKeys between them.
If you need more information about MySQL storage engines and how to know which one(s) are you using you will need to read the MySQL documentation, although the MySQL notes in our database docs also have some introductory information.
I suspect you had tables created with the MyISAM storage engine (the default for MySQL < 5.5) and since MySQL 5.5 defaults to InnoDB and you created new tables since then, you ended with a mix
You can change the table storage engine from phpMyadmin. Click on your teble name, go to the 'operations' tab, and change in the "Table Operation" box. Convert all or your storage engine to the same.
First thing to do should be checking table's storage engines. However, in my case storage engines were same (both INNODB). My issue was unmatched collation of tables. After setting default char-set of the Database, my problem has been solved.
You can check table details with;
SHOW TABLE STATUS WHERE Name = "yyyyyyy";
Once you figure out your table's (that will be ForeignKey) collation, you can set your database default char-set as shown here like this:
ALTER DATABASE my_db COLLATE = 'latin1_swedish_ci';
Look at the output of the command SHOW ENGINE INNODB STATUS in MySql or MariaDB console client (mariadb link, mysql link). It`s more informative than error message.
For example, it showed me this message:
...
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2021-09-20 18:27:08 7faea3ad1700 Error in foreign key constraint of table `my_db`.`django_admin_log`:
Alter table `my_db`.`django_admin_log` with foreign key constraint failed. Referenced table `my_db`.`profiles_userprofile` not found in the data dictionary near ' FOREIGN KEY (`user_id`) REFERENCES `profiles_userprofile` (`id`)'.
...
It said to me that I forgot to create migrations.
I am installing openerp at my local server, I have installed it and its dependences but after finishing its installation when i run server 'openerp-server' and acces it using 0.0.0.0:8069/. I got the following error
OpenERP Server Error
Client Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/addons/web/http.py", line 195, in dispatch
response["result"] = method(self, **self.params)
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/addons/web/controllers/main.py", line 709, in get_list
return db_list(req)
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/addons/web/controllers/main.py", line 88, in db_list
dbs = proxy.list()
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/addons/web/session.py", line 31, in proxy_method
result = self.session.send(self.service_name, method, *args)
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/addons/web/session.py", line 104, in send
raise xmlrpclib.Fault(openerp.tools.ustr(e), formatted_info)
Server Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/addons/web/session.py", line 90, in send
return openerp.netsvc.dispatch_rpc(service_name, method, args)
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/netsvc.py", line 295, in dispatch_rpc
result = ExportService.getService(service_name).dispatch(method, params)
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/service/web_services.py", line 122, in dispatch
return fn(*params)
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/service/web_services.py", line 351, in exp_list
cr = db.cursor()
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/sql_db.py", line 477, in cursor
return Cursor(self._pool, self.dbname, serialized=serialized)
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/sql_db.py", line 183, in __init__
self._cnx = pool.borrow(dsn(dbname))
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/sql_db.py", line 378, in _locked
return fun(self, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/openerp-7.0_20130211_002141-py2.7.egg/openerp/sql_db.py", line 433, in borrow
result = psycopg2.connect(dsn=dsn, connection_factory=PsycoConnection)
File "/usr/lib/python2.7/dist-packages/psycopg2/__init__.py", line 179, in connect
connection_factory=connection_factory, async=async)
OperationalError: FATAL: role "ghrix" does not exist
I haven't recognize this error.
One more thing , I haven't edit OpenERP server configuration file . And if I have to edit this file then what are those changes.
Thanks.
This error indicates that OpenERP is trying to connect to the PostgreSQL database server using the "ghrix" user, which does not exist. This is probably the user under which you are starting the server.
If you have created a special database user for OpenERP you need to specify it on the command-line using --db_user=DB_USER (and in that case you probably also need --db_host=localhost and --db-password=YOUR_PASSWORD).
If you haven't created any database user yet, the easiest solution is probably to create one named ghrix, e.g.:
$ sudo su - postgres
$ createuser -s ghrix # -s to make a super-user that can create DBs
Note: Use ./openerp-server --help to see all possible startup parameters for the OpenERP server. You can also put the command-line options in a config file: just execute
$ ./openerp-server -s
and then edit the sample config file that is created in $HOME/.openerp_serverrc
Even though the question has been answered, the following is a concise tutorial on installing a production grade OpenERP Server, that also explains how to set up the database, manage access rights and configure your OpenERP installation:
http://www.theopensourcerer.com/2012/02/how-to-install-openerp-6-1-on-ubuntu-10-04-lts/
you should check two case
First case:
$ sudo su - postgres $ createuser -s ghrix
second case
fill the db user and db password in
/odoo/debian/odoo.conf
run odoo with this parameter
./odoo-bin -c /opt/odoo/debian/odoo.conf
If not resolved comment below i try to resolve it