Django error: OperationalError at /admin/auth/user/1/change/ [duplicate] - django

I was following the first app tutorial from the official Django docs and got this error when trying to save some changes made through the admin page. I did some research on it, but the possible solutions I was able to find, such as migrating the db, simply won't work. Just let me know if you want to see some specific part of my code.
Following is error:
OperationalError at /admin/polls/question/1/change/ no such table:
main.auth_user__old Request Method: POST Request
URL: http://127.0.0.1:8000/admin/polls/question/1/change/ Django
Version: 2.1.4 Exception Type: OperationalError Exception Value: no
such table: main.auth_user__old Exception
Location: /Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py
in execute, line 296 Python
Executable: /Users/gfioravante/Projects/test_app/ta_env/bin/python3
Python Version: 3.7.1 Python Path:
['/Users/gfioravante/Projects/test_app/test_app',
'/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python37.zip',
'/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
'/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload',
'/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages']
Server time: Wed, 5 Dec 2018 16:45:00 +0000
and the traceback:
Environment:
Request Method: POST Request URL:
http://127.0.0.1:8000/admin/polls/question/1/change/
Django Version: 2.1.4 Python Version: 3.7.1 Installed Applications:
['polls.apps.PollsConfig', 'django.contrib.admin',
'django.contrib.auth', 'django.contrib.contenttypes',
'django.contrib.sessions', 'django.contrib.messages',
'django.contrib.staticfiles'] Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in _execute
85. return self.cursor.execute(sql, params)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py"
in execute
296. return Database.Cursor.execute(self, query, params)
The above exception (no such table: main.auth_user__old) was the
direct cause of the following exception:
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/core/handlers/exception.py"
in inner
34. response = get_response(request)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/core/handlers/base.py"
in _get_response
126. response = self.process_exception_by_middleware(e, request)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/core/handlers/base.py"
in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
in wrapper
604. return self.admin_site.admin_view(view)(*args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/utils/decorators.py"
in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/views/decorators/cache.py"
in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/sites.py" in inner
223. return view(request, *args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
in change_view
1640. return self.changeform_view(request, object_id, form_url, extra_context)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/utils/decorators.py"
in _wrapper
45. return bound_method(*args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/utils/decorators.py"
in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
in changeform_view
1525. return self._changeform_view(request, object_id, form_url, extra_context)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
in _changeform_view
1571. self.log_change(request, new_object, change_message)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
in log_change
826. change_message=message,
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/models.py"
in log_action
35. change_message=change_message,
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/manager.py"
in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/query.py"
in create
413. obj.save(force_insert=True, using=self.db)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/base.py"
in save
718. force_update=force_update, update_fields=update_fields)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/base.py"
in save_base
748. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/base.py"
in _save_table
831. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/base.py"
in _do_insert
869. using=using, raw=raw)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/manager.py"
in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/query.py"
in _insert
1136. return query.get_compiler(using=using).execute_sql(return_id)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/sql/compiler.py"
in execute_sql
1289. cursor.execute(sql, params)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in execute
100. return super().execute(sql, params)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in execute
68. return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in _execute_with_wrappers
77. return executor(sql, params, many, context)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in _execute
85. return self.cursor.execute(sql, params)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/utils.py"
in exit
89. raise dj_exc_value.with_traceback(traceback) from exc_value
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in _execute
85. return self.cursor.execute(sql, params)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py"
in execute
296. return Database.Cursor.execute(self, query, params)
Exception Type: OperationalError at /admin/polls/question/1/change/
Exception Value: no such table: main.auth_user__old

Get rid of this issue easily maintaining the following steps:
keep django version 2.1.5 (the issue addressed in this version)
pip install django==2.1.5
Delete the SQLite db
Migrate again python manage.py makemigrations and then python manage.py migrate
Start the server python manage.py runserver
DONE!

I just came across this myself, it looks to be related to https://code.djangoproject.com/ticket/29182. For now, you can just downgrade your version of sqlite to a version prior to 2.6 (e.g. 2.5.1)

Just did this and it resolved the problem:
pip install Django --upgrade
Then:
python manage.py migrate
python manage.py makemigrations app
python manage.py migrate

Here is what I did to solve this problem:
Go to the virtual environment and install django#2.1.7
pip install django==2.1.7
Delete the db.sqlite3 file in your root folder.
Create the new db.sqlite3 in your root folder.
Re-run migrations:
python3 manage.py makemigrations
python3 manage.py migrate
Now it should be working all right.

The problem is caused by the modified behaviour of the ALTER TABLE RENAME statement in SQLite 3.26.0 (see compatiblity note). They also introduced the PRAGMA legacy_alter_table = ON statement in order to maintain the compatibility with previous versions. The upcoming Django release 2.1.5 utilizes the previously mentioned statement as a hotfix. It's expected on January 1, 2019.

go to this folder django/db/backends/sqlite3
backup schema.py file to another folder
open the original schema.py in a text editor
there you can see a code snippet like
def __enter__(self):
# Some SQLite schema alterations need foreign key constraints to be
# disabled. Enforce it here for the duration of the schema edition.
if not self.connection.disable_constraint_checking():
raise NotSupportedError(
'SQLite schema editor cannot be used while foreign key '
'constraint checks are enabled. Make sure to disable them '
'before entering a transaction.atomic() context because '
'SQLite3 does not support disabling them in the middle of '
'a multi-statement transaction.'
)
self.connection.cursor().execute('PRAGMA legacy_alter_table = ON')
return super().__enter__()
comment them and paste the following code snippet
def __enter__(self):
# Some SQLite schema alterations need foreign key constraints to be
# disabled. Enforce it here for the duration of the transaction.
self.connection.disable_constraint_checking()
self.connection.cursor().execute('PRAGMA legacy_alter_table = ON')
return super().__enter__()
This worked for me. (the backup for the schema.py is in case the work go wrong ; D
)
for more info
https://github.com/django/django/pull/10733/commits/c8ffdbe514b55ff5c9a2b8cb8bbdf2d3978c188f#diff-0c8f495bfee773ab7b5409533bd6d7ef

First, stop the server and delete db.sqlite3.
Then, you need to run:
python manage.py makemigrations
python manage.py migrate
After running this command you need to create super user. To Create
Super User, run:
python manage.py createsuperuser
Enter the super user details there.
Run your server again.
There you go.

I solved the problem by upgrading Django from 2.1.4 to 2.1.5 by running
pip install --upgrade django==2.1.5
but I had to rebuild the project anew, because the bug seems to be somehow related to the objects I inserted into the database by using the old version of Django.
UPDATE:
Instead of deleting the entire project, it was sufficient to delete only the database. And then to run
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser

In my case, it was because of my django version (that was 2.1)
Install higher version (2.1.5+ or higher)
Delete db.sqlite3, and everything in migration folder except __init__.py
Run these commands:
pip install django==2.1.5 --upgrade
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver

Even after upgrading to the latest Django 2.2.12 and running either migrate or the official database rebuild script, I got the same error with __old_:
django.db.utils.IntegrityError: The row in table 'djangocms_blog_post_translation' with primary key '2' has an invalid foreign key: djangocms_blog_post_translation.master_id contains a value '2' that does not have a corresponding value in djangocms_blog_post__old.id.
Here's my hack:
dump the database contents to sql: sqlite3 my_db.db .dump > my_db.sql
run a regex over the sql output, replacing __old" ("id") with " ("id") DEFERRABLE INITIALLY DEFERRED
delete the old database file
load the modified sql into a new database: sqlite3 my_db.db < my_db.sql
??? & profit

keep django version 2.1.5
This issue is adressed only in this version of Django
pip install django==2.1.5
Delete the SQLite db
Run migration
Start the server python manage.py runserver
This solves the above issue

Same thing is happened to me, very frustrating. I use anaconda for my environments, I found that I couldn't remove sqlite without immediately reinstalling the most up to date version of sqlite. Trying an older version of django also didn't seem to work. The only solution that has worked for me is by using a PostgreSQL database. It's certainly not ideal but I am planning on utilising the PostgreSQL database in the future so this wasn't a complete waste of time. If you find yourself in the same place as I was then this video may be helpful if you want to know how to connect the PostgreSQL database with your django project.
You'll need to install the postgreSQL database before actually making the changes in settings.py, the installation is more of less clicking Next on all the options. However, remember the username and password you use during installation.

Open => /YourAppFolder/migrations/ You would to see the migrating files just like '0001_initial.py' delete all of these files. And run the follwing command
1- python manage.py makemigrations
2- python manage.py migrate
Hope, it must solve your problem

For the above problem and solution is:
1) Go to the terminal and type in pip install django==2.1.7 or the latest version of django
2) After the installation,In the terminal type in python manage.py makemigrations,and then python manage.py migrate
3) In the terminal,Start the server with code python manage.py runserver
4) Login to the admin server with the password and the add the product,It will successfully add the product.

For others who don't want to downgrade any software, you can head into your settings.py file and in the DATABASES dict, you can replace .sqlit3 with .postgresql, and right underneath it change the db.sqlit3 to db.sql. This switches your default db to using postgreSQL.
In doing so, you'll need to pip install psycopg2.
Delete your db.sqlite3 file (if you have one/don't care about losing what's in it) and everything else that isn't the __init__.py file in your app's migration folder. Once you've done all of that, you can run python manage.py makemigrations and python manage.py migrate and then it should work :)
Hope I was able to help someone!

First, update django version:
pip install django --upgrade
then
./manage.py makemigration
./manage.py migrate
./manage.py runserver

There are just 4 things I did on command line and it fixed mine.
ctrl + c (stop server)
py manage.py makemigrations
py manage.py migrate
py manage.py runserver (start server)

I had the same issue except that I had 2 sqlite databases and custom database router. I managed to get it working by downgrading Django to 1.11.20 and no need to recreate the databases.

For those who cannot resolve this error with above answers, if you had made your app with its name “main”, this error may occur cause of same app name issue. So try to change your app name “main” to another.

you need to upgrade Django, this issue has been fixed in this PR https://github.com/django/django/pull/10733

I solved the problem by changing some of my models. I had one named project and one named projects. The database tables got confused and threw me this error.

I have solved this issue using below :
1) Delete the db.sqlit3
2) app's directory delete everything in
pycache
3) manage.py makemigrations, manage.py migrate, manage.py createsuperuser and then manage.py runserver.

I had the same issue and fixed it by doing the below:
1) Get the latest django version
2) get the latest SQL Lite version
3) delete db.sqlite3 file from your project
4) Make a small change to the models.py (e.g. change the size of a field)
5) generate a new db.sqllite3 file by running the makemigrations & migrate commands
6) import the newly created db.sqllite3 file into SQL Lite

I installed/downgraded django to 2.2 version ,this removed django 3.x
pip install django==2.2
and then I deleted db.sqlite file and then
I tried
python manage.py makemigrations,
python manage.py migrate
python manage.py creatingsuperuser.

Upgrade Django
pip install Django --upgrade
Delete the db.sqlite3 file the root folder of your project.
Create the new db.sqlite3 in your root folder by re-running migrations.
python3 manage.py makemigrations
Migrate
python3 manage.py migrate
It may work with just this or you may need to create a new superuser if it was deleted.
Check for your superuser using
python manage.py shell
from django.contrib.auth.models import User
User.objects.filter(is_superuser=True)
If <QuerySet []> appears there is no user.
Else check if your user exists.
If your user does not exist create one using
python manage.py createsuperuser

Steps:
Uninstall current Django from your ENV. Just delete the folder "anaconda3/envs/yourenv/lib/python3.7/site-packages/Django all versions..
Note: Only for Anaconda users, other users should figure out how to uninstall a package from your ENV.
Go to https://github.com/django/django.
Download the repo as zip file.
Extract zip.
Switch to your ENV.
Enter the extracted folder.
Run "python setup.py install" And install Django.
Delete your previous db.sqlite3 file. Now apply the migrations again to create a new db.sqlite3 file.
Note: I don't know how to fix previous dbfile and prevent data loss. So please tell me if you know.
Run Server.
Congrats! It works fine now.
Update to latest django in January from the official Django release.

Please check if you haven't deleted the migration folder from your app
if deleted try to restore the folder and remove migration files or
if deleted permanently create app and copy paste your work and
then
1. Delete db.sqlite3
2. python manage.py makemigrations
3. python manage.py migrate
4. python manage.py createsuperuser
HTH :)

Delete db.sqlite3
makemigrations & migrate
Create new super user
This works for me

Note: Do not follow this trick if you have some personal data in Sqlite3 DB as you're going to delete Sqlite3 DB
I know many answers are given to this question but only this trick help me to solve this issue as I'm beginner at python and learning Django.
Stopped the django webserver running, Ctrl-C
Delete the db.sqlite3
Uninstalled Django old verison
Install latest version of Django with “pip install django”
Delete all migrations from all apps of your project
Now run these commands in terminal
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser ( provide super-user credentials )
python manage.py runserver
Now finally login to admin panel with updated super-user's credentials and try to add record.
Same suggestions at this link by someone

django-2.2.7
This worked for me -
1) Delete db.sqlite3.
2) Within each app, within the migrations folder, delete everything other than __init__.py .
3) Within each app,delete __pycache__ folder.
I am not sure if you had to do it for all apps or just the concerned app, but this worked for me.

Related

When I try to add new category in django admin, OperationalError at /admin/mediaportalapp/category/add/ [duplicate]

I was following the first app tutorial from the official Django docs and got this error when trying to save some changes made through the admin page. I did some research on it, but the possible solutions I was able to find, such as migrating the db, simply won't work. Just let me know if you want to see some specific part of my code.
Following is error:
OperationalError at /admin/polls/question/1/change/ no such table:
main.auth_user__old Request Method: POST Request
URL: http://127.0.0.1:8000/admin/polls/question/1/change/ Django
Version: 2.1.4 Exception Type: OperationalError Exception Value: no
such table: main.auth_user__old Exception
Location: /Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py
in execute, line 296 Python
Executable: /Users/gfioravante/Projects/test_app/ta_env/bin/python3
Python Version: 3.7.1 Python Path:
['/Users/gfioravante/Projects/test_app/test_app',
'/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python37.zip',
'/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
'/usr/local/Cellar/python/3.7.1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload',
'/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages']
Server time: Wed, 5 Dec 2018 16:45:00 +0000
and the traceback:
Environment:
Request Method: POST Request URL:
http://127.0.0.1:8000/admin/polls/question/1/change/
Django Version: 2.1.4 Python Version: 3.7.1 Installed Applications:
['polls.apps.PollsConfig', 'django.contrib.admin',
'django.contrib.auth', 'django.contrib.contenttypes',
'django.contrib.sessions', 'django.contrib.messages',
'django.contrib.staticfiles'] Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in _execute
85. return self.cursor.execute(sql, params)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py"
in execute
296. return Database.Cursor.execute(self, query, params)
The above exception (no such table: main.auth_user__old) was the
direct cause of the following exception:
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/core/handlers/exception.py"
in inner
34. response = get_response(request)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/core/handlers/base.py"
in _get_response
126. response = self.process_exception_by_middleware(e, request)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/core/handlers/base.py"
in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
in wrapper
604. return self.admin_site.admin_view(view)(*args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/utils/decorators.py"
in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/views/decorators/cache.py"
in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/sites.py" in inner
223. return view(request, *args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
in change_view
1640. return self.changeform_view(request, object_id, form_url, extra_context)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/utils/decorators.py"
in _wrapper
45. return bound_method(*args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/utils/decorators.py"
in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
in changeform_view
1525. return self._changeform_view(request, object_id, form_url, extra_context)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
in _changeform_view
1571. self.log_change(request, new_object, change_message)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/options.py"
in log_change
826. change_message=message,
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/contrib/admin/models.py"
in log_action
35. change_message=change_message,
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/manager.py"
in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/query.py"
in create
413. obj.save(force_insert=True, using=self.db)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/base.py"
in save
718. force_update=force_update, update_fields=update_fields)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/base.py"
in save_base
748. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/base.py"
in _save_table
831. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/base.py"
in _do_insert
869. using=using, raw=raw)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/manager.py"
in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/query.py"
in _insert
1136. return query.get_compiler(using=using).execute_sql(return_id)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/models/sql/compiler.py"
in execute_sql
1289. cursor.execute(sql, params)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in execute
100. return super().execute(sql, params)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in execute
68. return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in _execute_with_wrappers
77. return executor(sql, params, many, context)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in _execute
85. return self.cursor.execute(sql, params)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/utils.py"
in exit
89. raise dj_exc_value.with_traceback(traceback) from exc_value
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/utils.py"
in _execute
85. return self.cursor.execute(sql, params)
File
"/Users/gfioravante/Projects/test_app/ta_env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py"
in execute
296. return Database.Cursor.execute(self, query, params)
Exception Type: OperationalError at /admin/polls/question/1/change/
Exception Value: no such table: main.auth_user__old
Get rid of this issue easily maintaining the following steps:
keep django version 2.1.5 (the issue addressed in this version)
pip install django==2.1.5
Delete the SQLite db
Migrate again python manage.py makemigrations and then python manage.py migrate
Start the server python manage.py runserver
DONE!
I just came across this myself, it looks to be related to https://code.djangoproject.com/ticket/29182. For now, you can just downgrade your version of sqlite to a version prior to 2.6 (e.g. 2.5.1)
Just did this and it resolved the problem:
pip install Django --upgrade
Then:
python manage.py migrate
python manage.py makemigrations app
python manage.py migrate
Here is what I did to solve this problem:
Go to the virtual environment and install django#2.1.7
pip install django==2.1.7
Delete the db.sqlite3 file in your root folder.
Create the new db.sqlite3 in your root folder.
Re-run migrations:
python3 manage.py makemigrations
python3 manage.py migrate
Now it should be working all right.
The problem is caused by the modified behaviour of the ALTER TABLE RENAME statement in SQLite 3.26.0 (see compatiblity note). They also introduced the PRAGMA legacy_alter_table = ON statement in order to maintain the compatibility with previous versions. The upcoming Django release 2.1.5 utilizes the previously mentioned statement as a hotfix. It's expected on January 1, 2019.
go to this folder django/db/backends/sqlite3
backup schema.py file to another folder
open the original schema.py in a text editor
there you can see a code snippet like
def __enter__(self):
# Some SQLite schema alterations need foreign key constraints to be
# disabled. Enforce it here for the duration of the schema edition.
if not self.connection.disable_constraint_checking():
raise NotSupportedError(
'SQLite schema editor cannot be used while foreign key '
'constraint checks are enabled. Make sure to disable them '
'before entering a transaction.atomic() context because '
'SQLite3 does not support disabling them in the middle of '
'a multi-statement transaction.'
)
self.connection.cursor().execute('PRAGMA legacy_alter_table = ON')
return super().__enter__()
comment them and paste the following code snippet
def __enter__(self):
# Some SQLite schema alterations need foreign key constraints to be
# disabled. Enforce it here for the duration of the transaction.
self.connection.disable_constraint_checking()
self.connection.cursor().execute('PRAGMA legacy_alter_table = ON')
return super().__enter__()
This worked for me. (the backup for the schema.py is in case the work go wrong ; D
)
for more info
https://github.com/django/django/pull/10733/commits/c8ffdbe514b55ff5c9a2b8cb8bbdf2d3978c188f#diff-0c8f495bfee773ab7b5409533bd6d7ef
First, stop the server and delete db.sqlite3.
Then, you need to run:
python manage.py makemigrations
python manage.py migrate
After running this command you need to create super user. To Create
Super User, run:
python manage.py createsuperuser
Enter the super user details there.
Run your server again.
There you go.
I solved the problem by upgrading Django from 2.1.4 to 2.1.5 by running
pip install --upgrade django==2.1.5
but I had to rebuild the project anew, because the bug seems to be somehow related to the objects I inserted into the database by using the old version of Django.
UPDATE:
Instead of deleting the entire project, it was sufficient to delete only the database. And then to run
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
In my case, it was because of my django version (that was 2.1)
Install higher version (2.1.5+ or higher)
Delete db.sqlite3, and everything in migration folder except __init__.py
Run these commands:
pip install django==2.1.5 --upgrade
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver
Even after upgrading to the latest Django 2.2.12 and running either migrate or the official database rebuild script, I got the same error with __old_:
django.db.utils.IntegrityError: The row in table 'djangocms_blog_post_translation' with primary key '2' has an invalid foreign key: djangocms_blog_post_translation.master_id contains a value '2' that does not have a corresponding value in djangocms_blog_post__old.id.
Here's my hack:
dump the database contents to sql: sqlite3 my_db.db .dump > my_db.sql
run a regex over the sql output, replacing __old" ("id") with " ("id") DEFERRABLE INITIALLY DEFERRED
delete the old database file
load the modified sql into a new database: sqlite3 my_db.db < my_db.sql
??? & profit
keep django version 2.1.5
This issue is adressed only in this version of Django
pip install django==2.1.5
Delete the SQLite db
Run migration
Start the server python manage.py runserver
This solves the above issue
Same thing is happened to me, very frustrating. I use anaconda for my environments, I found that I couldn't remove sqlite without immediately reinstalling the most up to date version of sqlite. Trying an older version of django also didn't seem to work. The only solution that has worked for me is by using a PostgreSQL database. It's certainly not ideal but I am planning on utilising the PostgreSQL database in the future so this wasn't a complete waste of time. If you find yourself in the same place as I was then this video may be helpful if you want to know how to connect the PostgreSQL database with your django project.
You'll need to install the postgreSQL database before actually making the changes in settings.py, the installation is more of less clicking Next on all the options. However, remember the username and password you use during installation.
Open => /YourAppFolder/migrations/ You would to see the migrating files just like '0001_initial.py' delete all of these files. And run the follwing command
1- python manage.py makemigrations
2- python manage.py migrate
Hope, it must solve your problem
For the above problem and solution is:
1) Go to the terminal and type in pip install django==2.1.7 or the latest version of django
2) After the installation,In the terminal type in python manage.py makemigrations,and then python manage.py migrate
3) In the terminal,Start the server with code python manage.py runserver
4) Login to the admin server with the password and the add the product,It will successfully add the product.
For others who don't want to downgrade any software, you can head into your settings.py file and in the DATABASES dict, you can replace .sqlit3 with .postgresql, and right underneath it change the db.sqlit3 to db.sql. This switches your default db to using postgreSQL.
In doing so, you'll need to pip install psycopg2.
Delete your db.sqlite3 file (if you have one/don't care about losing what's in it) and everything else that isn't the __init__.py file in your app's migration folder. Once you've done all of that, you can run python manage.py makemigrations and python manage.py migrate and then it should work :)
Hope I was able to help someone!
First, update django version:
pip install django --upgrade
then
./manage.py makemigration
./manage.py migrate
./manage.py runserver
There are just 4 things I did on command line and it fixed mine.
ctrl + c (stop server)
py manage.py makemigrations
py manage.py migrate
py manage.py runserver (start server)
I had the same issue except that I had 2 sqlite databases and custom database router. I managed to get it working by downgrading Django to 1.11.20 and no need to recreate the databases.
For those who cannot resolve this error with above answers, if you had made your app with its name “main”, this error may occur cause of same app name issue. So try to change your app name “main” to another.
you need to upgrade Django, this issue has been fixed in this PR https://github.com/django/django/pull/10733
I solved the problem by changing some of my models. I had one named project and one named projects. The database tables got confused and threw me this error.
I have solved this issue using below :
1) Delete the db.sqlit3
2) app's directory delete everything in
pycache
3) manage.py makemigrations, manage.py migrate, manage.py createsuperuser and then manage.py runserver.
I had the same issue and fixed it by doing the below:
1) Get the latest django version
2) get the latest SQL Lite version
3) delete db.sqlite3 file from your project
4) Make a small change to the models.py (e.g. change the size of a field)
5) generate a new db.sqllite3 file by running the makemigrations & migrate commands
6) import the newly created db.sqllite3 file into SQL Lite
I installed/downgraded django to 2.2 version ,this removed django 3.x
pip install django==2.2
and then I deleted db.sqlite file and then
I tried
python manage.py makemigrations,
python manage.py migrate
python manage.py creatingsuperuser.
Upgrade Django
pip install Django --upgrade
Delete the db.sqlite3 file the root folder of your project.
Create the new db.sqlite3 in your root folder by re-running migrations.
python3 manage.py makemigrations
Migrate
python3 manage.py migrate
It may work with just this or you may need to create a new superuser if it was deleted.
Check for your superuser using
python manage.py shell
from django.contrib.auth.models import User
User.objects.filter(is_superuser=True)
If <QuerySet []> appears there is no user.
Else check if your user exists.
If your user does not exist create one using
python manage.py createsuperuser
Steps:
Uninstall current Django from your ENV. Just delete the folder "anaconda3/envs/yourenv/lib/python3.7/site-packages/Django all versions..
Note: Only for Anaconda users, other users should figure out how to uninstall a package from your ENV.
Go to https://github.com/django/django.
Download the repo as zip file.
Extract zip.
Switch to your ENV.
Enter the extracted folder.
Run "python setup.py install" And install Django.
Delete your previous db.sqlite3 file. Now apply the migrations again to create a new db.sqlite3 file.
Note: I don't know how to fix previous dbfile and prevent data loss. So please tell me if you know.
Run Server.
Congrats! It works fine now.
Update to latest django in January from the official Django release.
Please check if you haven't deleted the migration folder from your app
if deleted try to restore the folder and remove migration files or
if deleted permanently create app and copy paste your work and
then
1. Delete db.sqlite3
2. python manage.py makemigrations
3. python manage.py migrate
4. python manage.py createsuperuser
HTH :)
Delete db.sqlite3
makemigrations & migrate
Create new super user
This works for me
Note: Do not follow this trick if you have some personal data in Sqlite3 DB as you're going to delete Sqlite3 DB
I know many answers are given to this question but only this trick help me to solve this issue as I'm beginner at python and learning Django.
Stopped the django webserver running, Ctrl-C
Delete the db.sqlite3
Uninstalled Django old verison
Install latest version of Django with “pip install django”
Delete all migrations from all apps of your project
Now run these commands in terminal
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser ( provide super-user credentials )
python manage.py runserver
Now finally login to admin panel with updated super-user's credentials and try to add record.
Same suggestions at this link by someone
django-2.2.7
This worked for me -
1) Delete db.sqlite3.
2) Within each app, within the migrations folder, delete everything other than __init__.py .
3) Within each app,delete __pycache__ folder.
I am not sure if you had to do it for all apps or just the concerned app, but this worked for me.

Django + heroku - import error on line that doesn't exist

I'm new to django (using python 2.7) and I was just trying to use heroku for the first time but I always get the following error:
remote: -----> Preparing static assets
remote: Collectstatic configuration error. To debug, run:
remote: $ heroku run python manage.py collectstatic --noinput
When I run that command, an import error regarding the django registration redux library shows up. I've had this problem before in Django and I fixed it by placing RequestSite under 'requests' and Site under 'models'. That solved the problem but the error still shows up in Heroku.
(venv) C:\Users\Carolina\Desktop\Coding\venv\project1>heroku run python manage.p
y collectstatic --noinput
Running python manage.py collectstatic --noinput on acla-acla... up, run.3645
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/_
_init__.py", line 350, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/_
_init__.py", line 324, in execute
django.setup()
File "/app/.heroku/python/lib/python2.7/site-packages/django/__init__.py", lin
e 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/app/.heroku/python/lib/python2.7/site-packages/django/apps/registry.py"
, line 115, in populate
app_config.ready()
File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/app
s.py", line 22, in ready
self.module.autodiscover()
File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/__i
nit__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/app/.heroku/python/lib/python2.7/site-packages/django/utils/module_load
ing.py", line 50, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/app/.heroku/python/lib/python2.7/importlib/__init__.py", line 37, in im
port_module
__import__(name)
File "/app/.heroku/python/lib/python2.7/site-packages/registration/admin.py",
line 2, in <module>
from django.contrib.sites.models import RequestSite
ImportError: cannot import name RequestSite
The thing is - that line doesn't exist. I went to venv/lib/site-packages/registration/admin.py and line 2 is this one:
from django.contrib import admin
from django.contrib.sites.requests import RequestSite # HERE
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from registration.models import RegistrationProfile
from registration.users import UsernameField
class RegistrationAdmin(admin.ModelAdmin):
actions = ['activate_users', 'resend_activation_email']
list_display = ('user', 'activation_key_expired')
raw_id_fields = ['user']
search_fields = ('user__{0}'.format(UsernameField()), 'user__first_name', 'user__last_name')
def activate_users(self, request, queryset):
"""
Activates the selected users, if they are not already
activated.
"""
for profile in queryset:
RegistrationProfile.objects.activate_user(profile.activation_key)
activate_users.short_description = _("Activate users")
def resend_activation_email(self, request, queryset):
"""
Re-sends activation emails for the selected users.
Note that this will *only* send activation emails for users
who are eligible to activate; emails will not be sent to users
whose activation keys have expired or who have already
activated.
"""
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
for profile in queryset:
if not profile.activation_key_expired():
profile.send_activation_email(site)
resend_activation_email.short_description = _("Re-send activation emails")
admin.site.register(RegistrationProfile, RegistrationAdmin)
This is what I get with pip freeze, just in case:
Django==1.9
django-crispy-forms==1.5.2
django-registration==2.0.3
django-registration-redux==1.2
django-tinymce==2.2.0
Pillow==3.0.0
requests==2.9.0
South==1.0.2
stripe==1.27.1
wheel==0.24.0
Anyone knows why this is happening? Thanks in advance!
EDIT ----
Ok, so the problem was the one mentioned by Daniel Roseman. The library is broken in pypi and I had to tell heroku to install it from github (where the package is fixed).
So, I went to my requirements.txt file and replaced this line:
django-registration-redux==1.2
with this one:
-e git://github.com/macropin/django-registration.git#egg=django-registration==1.2
(I also removed 'django-registration==2.0.3' because it is an old version of django-registration-redux and was creating problems).
Hope this helps people with the same issue!
It sounds like you edited the code for your locally installed copy of django-registration-redux. But that won't have any effect on Heroku, since the library will be installed directly from PyPI, according to the version in your requirements.txt.
If the library is really broken, you will need to fork it and point your requirements.txt to your fixed version. However, looking at the code on GitHub, it doesn't actually seem to be broken; you just need to update the version you are pointing to.

Why do I get a "auth_user does not exist"error when running "migrate" on a newly created django project with "registration redux" app installed?

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

Django South added model to admin but gives DatabaseError

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.

How to delete all data for one app in Django 1.4 now that reset is gone?

How do I delete all the data in the database for on Django app? In previous version manage.py reset APPNAME did the job, but that's been deprecated.
What are we supposed to do now if we want to delete all the data from an app using the command line?
reset and sqlreset were both just wrappers around other management commands. sqlreset in particular can be duplicate by simply running:
python manage.py sqlclear myapp
python manage.py sqlall myapp
reset only served to automatically run the result of sqlreset on the database. Personally, I think removing that is a fantastic idea. Still, if you want similar functionality, you can just pipe the output to your database's shell commands.
For PostgreSQL, for example:
python manage.py sqlclear myapp | psql mydatabase
python manage.py sqlall myapp | psql mydatabase
If you want single command that should work with most database types you can pipe the drop table statements, that sqlclear generates, to dbshell
python manage.py sqlclear myapp | python manage.py dbshell
from django.contrib.contenttypes.models import ContentType
for ct in ContentType.objects.all()
ct.model_class().objects.all().delete()
Now that Django integrates migrations by default, you first need to make migrations for your app are first unapplied then deleted.
Here is the command line that works at least with Django 1.8 (replacing by the application you want to delete all associated data and:
# First, update the DB so it thinks no migrations were applied to the app
python manage.py migrate --fake <app_name> zero
# Erase all migrations in the app folder
rm -r "<app_name>/migrations/*"
# Erase the application tables
python manage.py sqlclear <app_name> | python manage.py dbshell
# Recreate the app tables, that will be empty
python manage.py makemigrations <app_name>
python manage.py migrate <app_name>
DIY
If you want to do that from the command line, create the following custom command:
from django.core.management.base import AppCommand, CommandError
from django.utils.six.moves import input
from django.db import DEFAULT_DB_ALIAS, connections
class Command(AppCommand):
help = (
'Removes ALL DATA related to the given app from the database '
'by calling model.objects.all().delete() for all app models. '
'This also removes related data in other apps via cascade.'
)
def add_arguments(self, parser):
super(Command, self).add_arguments(parser)
parser.add_argument(
'--noinput', '--no-input',
action='store_false', dest='interactive', default=True,
help='Tells Django to NOT prompt the user for input of any kind.',
)
parser.add_argument(
'--database', action='store', dest='database', default=DEFAULT_DB_ALIAS,
help='Nominates a database to reset. Defaults to the "default" database.',
)
def handle_app_config(self, app_config, **options):
app_label = app_config.label
database = options['database']
interactive = options['interactive']
db_name = connections[database].settings_dict['NAME']
confirm = (ask_confirmation(app_label, db_name)
if interactive else 'yes')
if confirm == 'yes':
for model in app_config.get_models():
model.objects.using(database).all().delete()
self.stdout.write('Reset done.\n')
else:
self.stdout.write("Reset cancelled.\n")
def ask_confirmation(app_label, db_name):
return input("""You have requested a reset of the application {app_label}.
This will IRREVERSIBLY DESTROY all data related to the app currently in
the {db_name} database, and return each table to empty state.
Are you sure you want to do this?
Type 'yes' to continue, or 'no' to cancel: """.format(**locals()))
Copy it to app/management/commands folder in any of your apps folders and run it with
./manage.py app_db_tables_reset any_installed_app_name
Ready-made package
The command is available in the django_commands package, you can install it with
pip install git+http://github.com/mrts/django-commands.git
and add it to INSTALLED_APPS to activate the command.
Tested with Django 1.9, it may or may not work with 1.8.