I changed my models and made migrations. Then i changed my models another one time and when try python manage.py migrate i get error:
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, shop
Running migrations:
Applying shop.0004_auto_20180128_1331...Traceback (most recent call last):
File "/home/morilon/dj/intshop/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 83, in _execute
return self.cursor.execute(sql)
File "/home/morilon/dj/intshop/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 301, in execute
return Database.Cursor.execute(self, query)
sqlite3.OperationalError: table "shop_brand" already exists
So my question is - how can i delete table "shop_brand"???
I already tried flush and sqlflush but that only delete data from table but not actually table "shop_brand".
I use django 2.0.1 and python 3.6
Use the dbshell command
python manage.py dbshell
then while in the shell, depending on what database you are using, you type the command to show tables to identify the table you want to drop.
For instance, for sqlite, you would use
.tables
still in the shell, you can use SQL command to drop the table
DROP TABLE shop_brand;
Related
Am trying to load some generated data into Django without disrupting the existing data in the site. What I have:
Saved the data as a valid JSON (validated here).
The JSON format matches the Django documentation. In previous attempts I also aligned it to the Django documentation here (slightly different field order, the result was the same).
Output errors I'm receiving are very generic and not helpful, even with verbosity=3.
The Error Prompt
Operations to perform:
Apply all migrations: workoutprogrammes
Running migrations:
Applying workoutprogrammes.0005_auto_20220415_2021...Loading '/Users/Robert/Desktop/Projects/Powerlifts/src/workoutprogrammes/fixtures/datafile_2' fixtures...
Checking '/Users/Robert/Desktop/Projects/Powerlifts/src/workoutprogrammes/fixtures' for fixtures...
Installing json fixture 'datafile_2' from '/Users/Robert/Desktop/Projects/Powerlifts/src/workoutprogrammes/fixtures'.
Traceback (most recent call last):
File "/Users/Robert/Desktop/Projects/Powerlifts/venv/lib/python3.8/site-packages/django/core/serializers/json.py", line 70, in Deserializer
yield from PythonDeserializer(objects, **options)
File "/Users/Robert/Desktop/Projects/Powerlifts/venv/lib/python3.8/site-packages/django/core/serializers/python.py", line 93, in Deserializer
Model = _get_model(d["model"])
KeyError: 'model'
The above exception was the direct cause of the following exception:... text continues on...
for obj in objects:
File "/Users/Robert/Desktop/Projects/Powerlifts/venv/lib/python3.8/site-packages/django/core/serializers/json.py", line 74, in Deserializer
raise DeserializationError() from exc
django.core.serializers.base.DeserializationError: Problem installing fixture '/Users/Robert/Desktop/Projects/Powerlifts/src/workoutprogrammes/fixtures/datafile_2.json':
auto_2022_migration.py file:
from django.db import migrations
from django.core.management import call_command
def db_migration(apps, schema_editor):
call_command('loaddata', '/filename.json', verbosity=3)
class Migration(migrations.Migration):
dependencies = [('workoutprogrammes', '0004_extable_delete_ex_table'),]
operations = [migrations.RunPython(db_migration),]
JSON file extract (start... end)
NB: all my PKs are UUIDs generated from postgresql
[{"pk":"af82d5f4-2814-4d52-b2b1-6add6cf18d3c","model":"workoutprogrammes.ex_table","fields":{"exercise_name":"Cable Alternating Front Raise","utility":"Auxiliary","mechanics":"Isolated","force":"Push","levator_scapulae":"Stabilisers",..."obliques":"Stabilisers","psoas_major":""}}]
I'm not sure what the original error was. I suspect it had to do with either editing the table/schema using psql separately from Django, OR using the somewhat outdated uuid-ossp package instead of pgcrypto package (native to Djagno via CryptoExtension()). I was never able to confirm. I did however manage to get it working by:
Deleting the table (schema, data) using psql and the app using Django. Creating a new app in Django.
Load the prev model data into this new_app/models.py. Make new migration file, first updating the CryptoExtension() operation before committing the migration.
Create Fixtures directory and relevant file (per Django specs, validated JSON online.
Validate my UUIDs online
Load the fixture data into the app. python3 manage.py loaddata /path/to/data/file_name.json
Given a newly created django project with the following installed apps:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'registration',
)
When I run ./manage.py migrate for the first time I get the following error:
Operations to perform:
Synchronize unmigrated apps: staticfiles, messages, registration
Apply all migrations: sessions, admin, auth, contenttypes
Synchronizing apps without migrations:
Creating tables...
Creating table registration_registrationprofile
Running deferred SQL...
Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/tcosta/Virtualenvs/django_project/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/Users/tcosta/Virtualenvs/django_project/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/tcosta/Virtualenvs/django_project/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/tcosta/Virtualenvs/django_project/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute
output = self.handle(*args, **options)
File "/Users/tcosta/Virtualenvs/django_project/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/tcosta/Virtualenvs/django_project/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 317, in sync_apps
cursor.execute(statement)
File "/Users/tcosta/Virtualenvs/django_project/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/Users/tcosta/Virtualenvs/django_project/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/Users/tcosta/Virtualenvs/django_project/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/tcosta/Virtualenvs/django_project/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```
It seems Django is trying to create the registration tables before the user table.
This erros does not happen if I comment the registration app and run migrate and then uncomment the registration app and run migrate again. However, that's not the right way of doing it, right?
After updating my Django version, I got this error and fix as running these two lines:
python manage.py migrate auth
python manage.py migrate
auth_user table inside auth model should run first I guess.
The problem is avoided when you do as Pedro Wagner suggests (auth_user error with Django 1.8 and syncdb / migrate):
Make sure that for all your apps, there exist initial migrations files by running:
manage.py makemigrations my_app
I'd do it not only for those that depend on auth because I think the problem is more general.
The root cause for this behaviour seems to me that for some reason
manage.py makemigrations
does not always create the initial migrations if they are not already there, contrary to:
manage.py makemigrations my_app
Unfortunately I cannot fathom the reasons for this asymmetry.
I think you just forgot to migrate your auth models. However, to do that, just type in the following command on your terminal.
python manage.py migrate
or
python manage.py migrate auth
Hope this settles your error in the program.
I think you needed to run:
python manage.py syncdb
and potentially you need to setup some dependencies? Probably not necessary after syncdb.
South 1 style (Django < 1.7)
class Migration:
depends_on = (
("accounts", "0001"),
)
def forwards(self):
....
South 2 style (Django >= 1.7)
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("accounts", "0001")]
Once you create a migration for your app it will automatically add the necessary dependencies. So in this case just run ./manage.py makemigrations registration.
Please check the registration/migrations/0001_initial.py file and you should see something like this:
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
This means you need to create migrations for all your apps with any kind of dependency.
I had this problem too, solved it by replacing old registration with one that includes pull #25:
pip install git+https://github.com/macropin/django-registration.git#v1.2c0
you have not migrated your models
python manage.py makemigrations my_app_name
for mac os
python3 manage.py makemigrations my_app
I am working with Postgres on a Django app and I want to make a model change, resetting a row so it is no longer the primary key.
This is what my model currently looks like in Django:
class Meeting(TimeStampedModel):
row = models.CharField(max_length=20, primary_key=True)
total_items = models.IntegerField()
I have run django-admin.py flush to remove all data from the database. If I run python manage.py makemigrations I see No changes detected. So we are starting from a clean base.
Now I edit row in models.py so it is no longer the primary key:
row = models.CharField(max_length=20)
And run python manage.py makemigrations and set 1 as the default when asked:
You are trying to add a non-nullable field 'id' to meeting without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
Select an option: 1
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now()
>>> 1
Migrations for 'frontend':
0007_auto_20150305_1129.py:
- Add field id to meeting
- Alter field row on meeting
That seems to run OK. Then if I run python manage.py migrate:
$ python manage.py migrate
Operations to perform:
Synchronize unmigrated apps: debug_toolbar
Apply all migrations: contenttypes, frontend, sites, auth, sessions
Synchronizing apps without migrations:
Creating tables...
Installing custom SQL...
Installing indexes...
Running migrations:
Applying frontend.0007_auto_20150305_1129...Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/me/.virtualenvs/meetings/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
...
File "/Users/me/.virtualenvs/meetings/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "frontend_meeting"
Why is it telling me I have multiple default values?
Do I need to set a unique primary key value as a default - and if so, how can I do this?
This is what the migrations file looks like:
class Migration(migrations.Migration):
dependencies = [
('frontend', '0006_auto_20150305_1050'),
]
operations = [
migrations.AddField(
model_name='meeting',
name='id',
field=models.AutoField(auto_created=True, primary_key=True, default=1, serialize=False, verbose_name='ID'),
preserve_default=False,
),
migrations.AlterField(
model_name='meeting',
name='row',
field=models.CharField(max_length=20),
preserve_default=True,
),
]
Try to use an intermediate migration to achieve this:
1) Add id = models.IntegerField() to your model.
Run makemigrations and then migrate.
2) Remove primary_key=True from the 'row'-field, and also remove the 'id'-field. Again run makemigrations and migrate.
I've just started using south with an existing app, and after adding new models to the db, I can view the models in the admin, but when clicking on them to view the model details an error
I try to do the south equivalent of syncdb:
python manage.py schemamigration directory --initial
python manage.py migrate directory
where directory is the app name.
So when i try and view the model in admin I get the following:
Exception Type: DatabaseError
Exception Value: (1146, "Table 'omada.directory_drift' doesn't exist")
where Drift is the model I added to models.py, then registered in admin.py - omada is the site name.
Further Information:
Traceback from the django site ends with:
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.py" in execute
114. return self.cursor.execute(query, args) File "/usr/local/lib/python2.7/dist-packages/MySQL_python-1.2.4b5-py2.7-linux-i686.egg/MySQLdb/cursors.py" in execute
201. self.errorhandler(self, exc, value) File "/usr/local/lib/python2.7/dist-packages/MySQL_python-1.2.4b5-py2.7-linux-i686.egg/MySQLdb/connections.py" in defaulterrorhandler
36. raise errorclass, errorvalue
When executing
python manage.py migrate directory
I get an error that starts with:
FATAL ERROR - The following SQL query failed: CREATE TABLE `directory_building`
! Since you have a database that does not support running
! schema-altering statements in transactions, we have had
! to leave it in an interim state between migrations.
which doesn't sound very promising :S, and ends with:
File "/usr/local/lib/python2.7/dist-packages/MySQL_python-1.2.4b5-py2.7-linux-i686.egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
django.db.utils.DatabaseError: (1050, "Table 'directory_building' already exists")
Thanks in advance to everyone who takes the time to read this and offer help!
You may find this guide useful.
Since you are only starting with South I would advice to start all over:
Drop your south table (south_migrationhistory) from your database
Delete the migrations from the app.migrations folder
Follow the guide
It is quite easy to get South in a bad state so you just need to get some experience with it. You however can't live without it as your projects grow in size.
I'm trying to delete a table hosted in heroku. Because it is in the shared database I can't connect to postgres directly to perform sentence. I execute delete through django shell. Issue is that table name is in uppercase and, for unknow reason, django try to delete it in lower cases:
>>> sql = '''drop table campings_horesEntrega cascade; <---see uppercases
... drop table campings_horesRecollida; '''
>>>
>>> from django.db import connections, transaction
>>> cursor = connections['default'].cursor()
>>> cursor.execute(sql)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/app/.heroku/venv/lib/python2.7/site-packages/django/db/backends/util.py", line 40, in execute
return self.cursor.execute(sql, params)
File "/app/.heroku/venv/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 52, in execute
return self.cursor.execute(query, args)
DatabaseError: table "campings_horesentrega" does not exist <--- see lowercases
someone has a workaround to my issue?
thanks a lot.
You need to wrap your table names in quotes if you want postgres to respect case.
DROP TABLE "campings_horesEntrega" CASCADE;