i'm new in django
i want to create a businessplan application
i create 3 classes in my models file "models.py"
when i run python manage.py migrates
it show me this errors:
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\hp\PycharmProjects\business\lib\site-packages\django\core\management\__init__.py",
line 401, in execute_from_command_line
utility.execute()
File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\core\management\__init__.py",
line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\core\management\base.py", line
328, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\core\management\base.py", line
369, in execute
output = self.handle(*args, **options)
File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\core\management\base.py", line
83, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\hp\PycharmProjects\business\lib\site-
packages\django\core\management\commands\migrate.py", line 89, in handle
executor.loader.check_consistent_history(connection)
File "C:\Users\hp\PycharmProjects\business\lib\site-packages\django\db\migrations\loader.py", line
295, in check_consistent_history
raise InconsistentMigrationHistory(
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied
before its dependency businessplan.0001_initial on database 'de
fault'.
this is my models.py :
it contain 4 classes Entrepreneur ,Admin , User(abstract) and projet:
from django.db import models
from django.contrib.auth.models import *
#user
class CustomUser(AbstractUser):
user_type=((1,"admin"),(2,"staff"))
user_type=models.CharField(default=1,choices=user_type,max_length=10)
# Entrepreneur
class Entrepreneur(models.Model):
id_models= models.IntegerField(primary_key=True)
admin=models.OneToOneField(CustomUser,on_delete=models.CASCADE)
nom_et_prenom=models.CharField(max_length=50)
date_naissance=models.DateField()
adresse_entr=models.CharField(max_length=20)
telephone=models.IntegerField()
statut_social=(('ce','celébataire'),
('ma','marié'),
('di','divorcé'),
('ve','veuf'),
)
occupation=models.CharField(max_length=50)
niveau_scolaire=(
('pri','primaire'),
('sec','secondaire'),
('cap','certificat aptitude professionel'),
('btp','brevet technicien professionel'),
('bts','brevet technicien superieur'),
('lic','license'),
('mai','maitrise'),
('mas','mastere'),
('doc','doctorat'),
)
niveau_scolaire=models.CharField(default='ser',choices=niveau_scolaire,max_length=50)
annnee_exp=models.IntegerField()
email=models.CharField(max_length=255)
password=models.CharField(max_length=255)
#Projet
class Projet(models.Model):
id_models=models.IntegerField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
nom_projet=models.CharField(max_length=30)
lieu_implantation=models.CharField(max_length=20)
type_projet=(
('ser','service'),
('com','commerce'),
('agr','agricuture'),
('ind','industrie'),
('IT','technologie information'),
('art','artisanat'),
('tor','tourisme'),
)
type_projet=models.CharField(default='ser',choices=type_projet,max_length=50)
produit=models.CharField(max_length=50)
id_promoteur=models.ForeignKey(Entrepreneur,on_delete=models.CASCADE)
#admin
class Admin(models.Model):
id_admin=models.AutoField(primary_key=True)
name=models.CharField(max_length=255)
email=models.CharField(max_length=255)
password=models.CharField(max_length=255)
objects=models.Manager()
first i run makemigration command and everythings is ok
but when i run migrate command it's not ok
First of all delete the migration files under the migrations folder of the app excluding the init file.If this will not work then do the same process and delete rows related to that app in django migrartions table. Then try to migrate. It will work. Happy CODING :D
You can delete the database then migration files, then make migrations and migrate to have a new consistent database. Don't forget to store any valuable data you have in the database.
solution is that delete all migration file from app/migrations folder.
hit python3 manage.py makemigration
It's create fresh migration file
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'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 started using Flask-Migrate today and installed it on a test project.
However i am getting following error:
alembic.util.exc.CommandError: Can't locate revision identified by
'e39d16e62810'
Steps to reproduce:
run "python create_db.py"
run "flask db init"
add column "name" to Entry-model
run "flask db migrate"
EDIT:
After removing migrations directory and repeating the process i am getting the same error after running "flask db migrate".
I also tried using a manage.py file with flask-script --> same issue
Error:
(venv_mentz) H:\Flask-API-Test>python manage.py db migrate
INFO [alembic.runtime.migration] Context impl SQLiteImpl.
INFO [alembic.runtime.migration] Will assume non-transactional DDL.
Traceback (most recent call last):
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\base.py", line 143, in _catch_revision_errors
yield
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\base.py", line 206, in get_revisions
return self.revision_map.get_revisions(id_)
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 299, in get_revisions
return sum([self.get_revisions(id_elem) for id_elem in id_], ())
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 299, in <listcomp>
return sum([self.get_revisions(id_elem) for id_elem in id_], ())
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 304, in get_revisions
for rev_id in resolved_id)
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 304, in <genexpr>
for rev_id in resolved_id)
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 362, in _revision_for_ident
resolved_id)
alembic.script.revision.ResolutionError: No such revision or branch 'e39d16e62810'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 14, in <module>
manager.run()
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\flask_script\__init__.py", line 417, in run
result = self.handle(argv[0], argv[1:])
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\flask_script\__init__.py", line 386, in handle
res = handle(*args, **config)
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\flask_script\commands.py", line 216, in __call__
return self.run(*args, **kwargs)
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\flask_migrate\__init__.py", line 197, in migrate
version_path=version_path, rev_id=rev_id)
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\command.py", line 176, in revision
script_directory.run_env()
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\base.py", line 425, in run_env
util.load_python_file(self.dir, 'env.py')
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\util\pyfiles.py", line 81, in load_python_file
module = load_module_py(module_id, path)
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\util\compat.py", line 83, in load_module_py
spec.loader.exec_module(module)
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "migrations\env.py", line 87, in <module>
run_migrations_online()
File "migrations\env.py", line 80, in run_migrations_online
context.run_migrations()
File "<string>", line 8, in run_migrations
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\runtime\environment.py", line 836, in run_migrations
self.get_context().run_migrations(**kw)
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\runtime\migration.py", line 321, in run_migrations
for step in self._migrations_fn(heads, self):
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\command.py", line 156, in retrieve_migrations
revision_context.run_autogenerate(rev, context)
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\autogenerate\api.py", line 415, in run_autogenerate
self._run_environment(rev, migration_context, True)
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\autogenerate\api.py", line 425, in _run_environment
if set(self.script_directory.get_revisions(rev)) != \
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\base.py", line 206, in get_revisions
return self.revision_map.get_revisions(id_)
File "c:\users\marschall\appdata\local\programs\python\python36-32\Lib\contextlib.py", line 100, in __exit__
self.gen.throw(type, value, traceback)
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\base.py", line 174, in _catch_revision_errors
compat.raise_from_cause(util.CommandError(resolution))
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\util\compat.py", line 194, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=exc_value)
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\util\compat.py", line 187, in reraise
raise value.with_traceback(tb)
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\base.py", line 143, in _catch_revision_errors
yield
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\base.py", line 206, in get_revisions
return self.revision_map.get_revisions(id_)
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 299, in get_revisions
return sum([self.get_revisions(id_elem) for id_elem in id_], ())
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 299, in <listcomp>
return sum([self.get_revisions(id_elem) for id_elem in id_], ())
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 304, in get_revisions
for rev_id in resolved_id)
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 304, in <genexpr>
for rev_id in resolved_id)
File "H:\Flask-API-Test\venv_mentz\lib\site-packages\alembic\script\revision.py", line 362, in _revision_for_ident
resolved_id)
alembic.util.exc.CommandError: Can't locate revision identified by 'e39d16e62810'
My file structure looks like this:
app
-- views
----- __init__.py
----- main.py
-- __init__.py
-- config.py
-- models.py
instance
-- __init__.py
-- config.py
create_db.py
dev.db
run.py
My app factory:
from flask import Flask
from instance.config import app_config
from flask_migrate import Migrate
def create_app(config_name):
""" Creates a runnable app.
This app will be using the config with name "config_name".
"""
app = Flask(__name__)
# Loading the the config from instance folder with name "config_name"
app.config.from_object(app_config[config_name])
# Loading generic config from 'config.py'
app.config.from_pyfile('config.py')
# Registering this app at db
from app.models import db
db.init_app(app)
migrate = Migrate(app, db)
from app import models, views
return app
My run.py:
""" This script runs a the app with the given configuration. """
from app import create_app
# Configuration used to run the app
config_name = 'dev'
# Creating the app by using the required configuration
app = create_app(config_name)
if __name__ == '__main__':
app.run()
And my create_db.py file to create the database using models.py:
""" This script creates the database defined in app.models. """
from app import create_app
app = create_app('dev')
from app.models import db
# Telling SQLAlchemy what app should be used as the database model
with app.app_context():
db.create_all()
This is my models.py:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Entry(db.Model):
__tablename__ = 'Entries'
layer_id = db.Column(db.Integer, primary_key=True)
def __repr__(self):
return "ID: {}; text: {}".format(self.layer_id, self.text)
EDIT: manage.py:
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import create_app
from app import models
from app.models import db
app = create_app('dev')
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
you delete the migration directory but the version has been saved in the database, so you have to delete the version info in the dabase,
run
delete from alembic_version;
in mysql shell.
As suggested by #mirekphd, If this is a developing environment or a single app for test, just delete it, Else BACKUP the data in the table.
I tried this on flask and it worked:
python app.py db revision --rev-id e39d16e62810
python app.py db migrate
python app.py db upgrade
In my case I have accidentally deleted the most recent migration file but the alembic version (alembic_version) table refers to the deleted version.
So instead of droping the entire database, you can change the version_num field in the alembic_version table.
Following steps worked for me:
Find the head using db history
Update the version_num field to the head version.
run migrate using db migrate
upgrade the database db upgrade
Most of the time this happens, if you are at the development stage where you don't have much data to loose, you can drop the database and create a fresh one, alternatively, you can delete the migrations and begin the whole cycle again, for sqlite, it is all about deleting the sqlite file in your application, and beginning this cycle again. I hope to find the best solution to this verry soon.
In my case, I have accidentally deleted the most recent migration file but the alembic version (alembic_version) table refers to the deleted version.
I tried the following:
flask db revision --rev-id [revision-id]
flask db migrate
flask db upgrade
My problem was that another flask app was already connected to the same database, so I just created a new database, and changed:
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root#127.0.0.1:3306/newDataBaseName'
Delete the history entry from the database will solve the issue.
Error: alembic.util.exc.CommandError: Can't locate revision identified by 'e39d16e62810'
select * from alembic_version where version_num='e39d16e62810'
Option 1: Update the record with your latest revision id
update alembic_version set version_num='<your_version_num>' where version_num='e39d16e62810'
Option 2: Delete this record:
delete from alembic_version where version_num='e39d16e62810'
For my case reason for the error was the relative path to sqlite db.
Fixed it by specifying the absolute path
app.config['SQLALCHEMY_DATABASE_URI'] = f"sqlite:///{os.path.join(os.path.dirname(__file__), os.path.pardir, 'db.sqlite')}"
Yet another cause of problems - making two flask projects in the same virtual environment.
I tried to make fake twin project for performance testing.
copied crucial parts of the original project
created new database
made changes in configuration file to point to new database
flask db init,
flask db migrate
got this error at first migration.
Then I did only one thing - created new python environment for this twin project - and error disappeared.
PS. Maybe it is possible to create two flask projects in the same environment, but I was not able to find solution.
In my case, since I was in the initial phase, I had the luxury of deleting the database file directly i.e. in my project folder there was a .sqlite file, so I deleted it by right-clicking it.
But please keep in mind that I was in the initial phase, so I won't suggest this if you are
not in the starting phase.
I had the same error message but in my case it's because I used wrong database name in the connection string. Check your connection string
Error Message:
ERROR [root] Error: Can't locate revision identified by 'a80ab7ca5e1a'
Reason:
My connection string was:
mysql+pymysql://kaunda:kaunda#localhost:3306/smis
Instead of
mysql+pymysql://kaunda:kaunda#localhost:3306/WorkFolder
The revision identified by "a80ab7ca5e1a" belongs to the database "smis" not "WorkFolder"
Make sure you set FLASK_APP=app.py on windows or export FLASK_APP=app.py on MAC before running flask db init, then flask db migrate -m "message" and flask db upgrade. You can check this link for more info https://pypi.org/project/Flask-Migrate/
I've read already the existing answer about this problem in Stackoverflow. But none worked for me. When I run manage.py test, I get the following, although my website run fine!
$ ./manage.py test --verbosity=3
manage.py test --verbosity=3
nosetests --with-coverage --cover-package=project.iobserve.forms,project.iobserve.models,project.iobserve.views --verbosity=3
nose.config: INFO: Ignoring files matching ['^\\.', '^_', '^setup\\.py$']
nose.plugins.cover: INFO: Coverage report will include only packages: ['project.iobserve.forms', 'project.iobserve.models', 'project.iobserve.views']
Creating test database for alias 'default' ('test_iobserve')...
Got an error creating the test database: database "test_iobserve" already exists
Type 'yes' if you would like to try deleting the test database 'test_iobserve', or 'no' to cancel: yes
Destroying old test database 'default'...
Operations to perform:
Synchronize unmigrated apps: mptt, djangobower, iobserve, staticfiles, twitter, messages, leaflet, allauth, facebook, multiselectfield, django_nose, rest_framework, honeypot
Apply all migrations: account, sessions, admin, sites, auth, contenttypes, socialaccount
Synchronizing apps without migrations:
Running pre-migrate handlers for application admin
Running pre-migrate handlers for application contenttypes
Running pre-migrate handlers for application sites
Running pre-migrate handlers for application auth
Running pre-migrate handlers for application sessions
Running pre-migrate handlers for application rest_framework
Running pre-migrate handlers for application mptt
Running pre-migrate handlers for application djangobower
Running pre-migrate handlers for application honeypot
Running pre-migrate handlers for application leaflet
Running pre-migrate handlers for application allauth
Running pre-migrate handlers for application account
Running pre-migrate handlers for application socialaccount
Running pre-migrate handlers for application twitter
Running pre-migrate handlers for application facebook
Running pre-migrate handlers for application iobserve
Creating tables...
Creating table iobserve_person
Creating table iobserve_bibliographicreference
Creating table user_profile
Creating table iobserve_coordinates
Creating table iobserve_observingsite
Creating table iobserve_astronomicalorganisation
Creating table iobserve_building
Creating table iobserve_dome
Creating table iobserve_tool
Creating table iobserve_observingtool
Creating table iobserve_telescope
Creating table iobserve_toolcomponent
Creating table iobserve_mirror
Creating table iobserve_astronomicalcoordinates
Creating table iobserve_alias
Creating table iobserve_objecttype
Creating table iobserve_astronomicalflux
Creating table iobserve_astronomicalobject
Running deferred SQL...
Traceback (most recent call last):
File "manage.py", line 7, in <module>
execute_from_command_line(sys.argv)
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv
super(Command, self).run_from_argv(argv)
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/django/core/management/commands/test.py", line 74, in execute
super(Command, self).execute(*args, **options)
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute
output = self.handle(*args, **options)
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/django/core/management/commands/test.py", line 90, in handle
failures = test_runner.run_tests(test_labels)
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/django_nose/runner.py", line 350, in run_tests
result = self.run_suite(nose_argv)
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/django_nose/runner.py", line 297, in run_suite
addplugins=plugins_to_add)
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/nose/core.py", line 121, in __init__
**extra_args)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/main.py", line 95, in __init__
self.runTests()
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/nose/core.py", line 207, in runTests
result = self.testRunner.run(self.test)
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/nose/core.py", line 50, in run
wrapper = self.config.plugins.prepareTest(test)
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/nose/plugins/manager.py", line 99, in __call__
return self.call(*arg, **kw)
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/nose/plugins/manager.py", line 167, in simple
result = meth(*arg, **kw)
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/django_nose/plugin.py", line 76, in prepareTest
self.old_names = self.runner.setup_databases()
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/django_nose/runner.py", line 533, in setup_databases
return super(NoseTestSuiteRunner, self).setup_databases()
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/django/test/runner.py", line 166, in setup_databases
**kwargs
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/django/test/runner.py", line 370, in setup_databases
serialize=connection.settings_dict.get("TEST", {}).get("SERIALIZE", True),
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/django/db/backends/base/creation.py", line 368, in create_test_db
test_flush=not keepdb,
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/django/core/management/__init__.py", line 120, in call_command
return command.execute(*args, **defaults)
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute
output = self.handle(*args, **options)
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 179, in handle
created_models = self.sync_apps(connection, executor.loader.unmigrated_apps)
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 317, in sync_apps
cursor.execute(statement)
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/onekiloparsec/.virtualenvs/iobs-debug/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute
return self.cursor.execute(sql)
django.db.utils.ProgrammingError: relation "auth_user" does not exist
The only problematic line is the relationship between the UserProfile and the user in my models. Below the UserProfile model. I also ran makemigrations and migrate individually, sequentially, etc etc. But when I run tests, it fails. I really have no clue. Any help would be greatly appreciated!
from django.conf import settings
from django.db import models
from allauth.account.models import EmailAddress
from allauth.socialaccount.models import SocialAccount
import hashlib
class UserProfile(models.Model):
class Meta:
db_table = 'user_profile'
app_label = 'iobserve'
user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile')
def __unicode__(self):
return "{}'s profile".format(self.user.username)
def account_verified(self):
if self.user.is_authenticated:
result = EmailAddress.objects.filter(email=self.user.email)
if len(result):
return result[0].verified
return False
def profile_image_url(self):
fb_uid = SocialAccount.objects.filter(user_id=self.user.id, provider='facebook')
if len(fb_uid):
return "http://graph.facebook.com/{}/picture?width=40&height=40".format(fb_uid[0].uid)
return "http://www.gravatar.com/avatar/{}?s=40".format(hashlib.md5(self.user.email).hexdigest())
Your iobserve app doesn't have any migrations, and you can't have a relation, such as a OneToOneField, from an unmigrated app to a migrated app.
You need to run manage.py makemigrations iobserve to create the initial migrations for the iobserve app. Only when the initial migrations exist, will manage.py makemigrations without any app labels create new migrations for that app.
I created a model but after 'makemigrations' and 'syncdb' the table doesn't appear in the database.
This is the second model that I want to create and the first model was not a problem.
The command 'makemigrations' creates a .py file, but syncdb shows the message "No migrations to apply".
What am I doing wrong?
python manage.py makemigrations
Migrations for 'category':
0006_text.py:
- Create model text
root#BB:~/Documenten/BB$ python manage.py syncdb
Operations to perform:
Synchronize unmigrated apps: admin-tools, theming
Apply all migrations: admin, category, contenttypes, auth, sessions
Synchronizing apps without migrations:
Creating tables...
Installing custom SQL...
Installing indexes...
Running migrations:
No migrations to apply.
My models
from django.db import models
# Create your models here.
class textitem(models.Model):
bb_txt_lang = models.CharField(max_length=3)
bb_txt_cat = models.CharField(max_length=30)
bb_txt_title = models.CharField(max_length=50)
bb_txt_body = models.TextField()
bb_txt_footer = models.TextField()
# bb_txt_date_from = models.DateField()
# bb_txt_date_until= models.DateField()
bb_txt_status = models.BooleanField(default = False)
def __str__(self):
return self.bb_txt_title
class forum(models.Model):
bb_for_title = models.CharField(max_length=50)
bb_for_body = models.TextField()
bb_for_footer = models.TextField()
# bb_for_date_from = models.DateField()
# bb_for_date_until= models.DateField()
def __str__(self):
return self.bb_for_title
class category(models.Model):
bb_cat_lang = models.CharField(max_length=3)
bb_cat_desc = models.CharField(max_length=50)
# bb_cat_image = models.ImageField()
bb_cat_text = models.TextField()
bb_cat_prod = models.BooleanField(default = False)
bb_cat_sub = models.ForeignKey('category', null=True, blank=True )
def __str__(self):
return self.bb_cat_desc
The error code
biidbox#BiidBox:~/Documenten/BiidBox$ python manage.py migrate
Operations to perform:
Synchronize unmigrated apps: admin_tools, theming
Apply all migrations: admin, category, contenttypes, auth, sessions
Synchronizing apps without migrations:
Creating tables...
Installing custom SQL...
Installing indexes...
Running migrations:
Applying category.0002_auto_20141128_1502...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 160, in handle
executor.migrate(targets, plan, fake=options.get("fake", False))
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 63, in migrate
self.apply_migration(migration, fake=fake)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 97, in apply_migration
migration.apply(project_state, schema_editor)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 107, in apply
operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/fields.py", line 84, in database_forwards
schema_editor.remove_field(from_model, from_model._meta.get_field_by_name(self.name)[0])
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 439, in remove_field
self.execute(sql)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 99, in execute
cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 81, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "category_forum" does not exist
if you're using Django 1.7, which I assume since you're using makemigrations then syncdb is deprecated... you should be using migrate
https://docs.djangoproject.com/en/1.7/topics/migrations/#the-commands
see also:
https://docs.djangoproject.com/en/1.7/releases/1.7/#schema-migrations
When you make a fresh app with a fresh database, you run the commands in following order:
1) python manage.py syncdb
This creates all the tables that will be used by django (eg :auth_group, auth_user) etc.
You won't see your app's tables, after this command, in the database.
Then you do:
2) python manage.py makemigrations
This will run the initial migration and will detect all your new models.It just detects the models.Doesn't create tables in the database
After that,run the following command
3) python manage.py migrate
This will create your tables.
After you have done this, you just need to use (2) and (3) for any changes to happen.The changes could be creating new models or editing the schema of existing models, etc.
So now, in your question, when you ran python manage.py makemigration ,it detected your new model "text"
Now just run python manage.py migrate for the changes to take effect(in this case, to create table).
Hope this helps