"no such table" exception
Asked Answered
D

28

43

In Django I added models into models.py. After manage.py makemigrations, manage.py migrate raised this exception:

django.db.utils.OperationalError: no such table: auth_test_usertranslatorprofile

I removed all old migrations and run makemigrations and migrate again which seemed to work. It didn't help because when I click User customer profiles of User translator profiles it raises exception:

Request Method: GET
Request URL: http://127.0.0.1:8000/admin/auth_test/usertranslatorprofile/

Django Version: 1.8.7
Python Version: 2.7.10
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'auth_test')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')


Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in wrapper
  618.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
  110.                     response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
  57.         response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\sites.py" in inner
  233.             return view(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapper
  34.             return bound_func(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
  110.                     response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in bound_func
  30.                 return func.__get__(self, type(self))(*args2, **kwargs2)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in changelist_view
  1550.                 self.list_max_show_all, self.list_editable, self)
File "C:\Python27\lib\site-packages\django\contrib\admin\views\main.py" in __init__
  82.         self.get_results(request)
File "C:\Python27\lib\site-packages\django\contrib\admin\views\main.py" in get_results
  177.         result_count = paginator.count
File "C:\Python27\lib\site-packages\django\core\paginator.py" in _get_count
  72.                 self._count = self.object_list.count()
File "C:\Python27\lib\site-packages\django\db\models\query.py" in count
  318.         return self.query.get_count(using=self.db)
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in get_count
  466.         number = obj.get_aggregation(using, ['__count'])['__count']
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in get_aggregation
  447.         result = compiler.execute_sql(SINGLE)
File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  840.             cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py" in execute
  79.             return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py" in execute
  64.                 return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\utils.py" in __exit__
  98.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py" in execute
  64.                 return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
  318.         return Database.Cursor.execute(self, query, params)

Exception Type: OperationalError at /admin/auth_test/usertranslatorprofile/
Exception Value: no such table: auth_test_usertranslatorprofile

models.py:

from django.db import models
from django.contrib.auth.models import User

class Language(models.Model):
    shortcut = models.CharField(max_length=6)
    name = models.CharField(max_length=50)
    price_per_sign = models.FloatField()

class UserTranslatorProfile(models.Model):
    user = models.OneToOneField(User)
    languages = models.ManyToManyField(Language)
    price_per_word = models.FloatField()

class UserCustomerProfile(models.Model):
    user = models.OneToOneField(User)

admin.py:

from django import forms
from .models import Language
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class FreelancerRegistrationForm(forms.Form):
    language = forms.ModelChoiceField(queryset=Language.objects.all().order_by('shortcut'))

What is the problem?

Dora answered 31/12, 2015 at 16:1 Comment(8)
Did you try clearing your database and trying again? Your migration will try to create everything but some things already exist and will fail anyway.Bayne
Do you mean manage.py flush? Yes I did that but it does not helped. How can I clear the database?Dora
Could you run this in sql shell? select * from django_migrations where app='auth_test'; and post the output?Mouldon
@Mouldon I've executed the query in SQLite browser. It returned just one row: id:11; app:auth_test; name:0001_initial; applied: 2015-12-29 21:06:08.101000Dora
Can you post the auth_test.0001_initial migration in a gist?Mouldon
#61096242 I tried all the actions until I dig deeper myself and did It`s work) Picture, thet is is work hereAcaroid
Maybe using python3 manage.py migrate --fake #71386257Worthwhile
The answer by @bhskarc solved it for me #34549268Sodality
A
105

I solved the same problem with these steps :

  • Delete your database (db.sqlite3 in my case) in your project directory
  • Remove everything from __pycache__ folder under your project subdirectory
  • For the application you are trying to fix, go to the folder and clear migrations and __pycache__ directories

When you are sure you have cleared all the above files, run:

python manage.py makemigrations
python manage.py migrate
Answer answered 6/4, 2016 at 13:43 Comment(5)
reaching wits end: what if manage makemigrations is the thing throwing the "django.db.utils.OperationalError: no such table: ......" error?Arsine
I have the same problem after opening to > python manage.py shell and then typing > from model_name.models import model1,model2 and then after calling > model1.objects.all() I get the error -- django.db.utils.OperationalError: no such table: model1Wershba
This solution will "work", but it requires nuking your migrations folder, which will give you headaches in production, particularly at scale. If you've stumbled over this comment and you're only ever going to run your code on your home PC, you can dust yourself off and carry on using this answer. If your code is ever going to touch a production server and/or you're curious as to why this is a bad idea in production, check out link and then have a read of Terry Brown's solution.Ratter
@Ratter I tried manage,py migrate --run-syncdb as a poster below suggested and it worked. I tried messing with funny FieldSets and broke it somehow. Could you comment on this?Saintjust
For me switching to mysql from the sqlite helped. I was having similar issues. When I deleted the entire db.sqlite3 file and removed all __pycache__ files, and all the make migrations files, some of my tables were still missing. I figured that out using sqlite database browser. For me, taking mysql to production was more convenient, so any changes I've been making are working very well using the above two lines.Gaberdine
H
90

run below command. It solves me once this issue

manage.py migrate --run-syncdb

Helsinki answered 23/4, 2019 at 17:33 Comment(3)
#25772255Worthwhile
When I got this error then I check my own gist gist.github.com/AthifSaheer/96eaa10599a84169d8d7980900dce666, But today that not helped me. This command worked manage.py migrate --run-syncdb.Trompe
This solved my problem. I also noticed that I had to recreate super user using the command python3 manage.py createsuperuser in order to login to the admin panel againBinns
S
39

Another case wihch can generate the no such table error. If your views.py or similar executes code that tries to access the DB when imported, i.e. importing views.py has side effects, then starting from scratch won't work.

This happens when your code was working with an existing DB, and now you're trying to start without a DB. Just change views.py so it can be imported without side effects. If you don't want to fix the design, do something like:

from django.db.utils import OperationalError
format_list = [('', '(all)')]
geom_type_list = [('', '(all)')]
try:
    format_list.extend([(i[0],i[0]) 
        for i in Format.objects.values_list('name')])
    geom_type_list.extend([(i[0],i[0]) 
        for i in Geom_type.objects.values_list('name')])
except OperationalError:
    pass  # happens when db doesn't exist yet, views.py should be
          # importable without this side effect
Seve answered 8/4, 2016 at 15:41 Comment(7)
I think I have this issue, though where should the code snippet above be run? And what is Format and Geom_type? Looks like models but where do they reside? (I get "NameError: name 'Format' is not defined")Seidel
@Seidel the code goes at the start of views.py. Format and Geom_type were specific to my app. - I was trying to make a module level list of available Formats/Geom_Types, and that fails when the DB has yet to be created. If you're doing something similar, wrapping in a try:/except: like that might help.Seve
Thanks! Got it working though :) My views imported my forms in which a query was causing the problem. Worked if I commented it out until the database was up and running.Seidel
Could you post an example of what "views.py or similar executes code that tries to access the DB when imported" looks like? I'm unsure whether this is my case. Thanks!Gallice
After spending around 2 hours, reading and trying out countless things from SO, GitHub, whatever I could find.... . YOU SAVED ME. As with @Seidel in my forms.py I had used the values for populating the choices of the Char field. I had to use your code in my models.py also because one Model's choice depends on another model's unique values amongst rows. THANKS A LOT !!!!Ladonna
This saved me. I was running a async process that was sending alerts based on things in the database. Commented out that process in views.py, and BOOM migrations worked perfectly.Roryros
I had the same issue and this helped.Helotry
M
21

To solve it I did this (on Ubuntu, you'll need to adapt the commands for Windows):

1. Remove all the migration files

find . -path "*/migrations/*.py" -not -name "__init__.py" -delete

find . -path "*/migrations/*.pyc"  -delete

2. Delete db.sqlite3

rm db.sqlite3

3. Create and run the migrations:

python manage.py makemigrations
python manage.py migrate

4. Sync the database:

manage.py migrate --run-syncdb

Bit of a pain as you need to delete your database, but fine for a test system. Got all but the final step from this generally excellent resource: https://simpleisbetterthancomplex.com/tutorial/2016/07/26/how-to-reset-migrations.html

Mcclinton answered 13/10, 2019 at 9:20 Comment(4)
All answers point to just migrating, but key for me was deleting the db.sqlite3 in step 2!Mountainous
this is the wayOrchitis
Deleting the DB is not a good solution at all.Scansion
find . -path "*/migrations/*.py" -not -name "__init__.py" -delete is dangerous as it deletes django.db.migrations.migration content.Db
I
16

Using Django, I had to perform:

python manage.py migrate --run-syncdb

Inodorous answered 12/1, 2021 at 22:26 Comment(2)
Worked for me after after deleting the old migrations and rerunning the makemigrations , migrate failed.Thickness
@Thickness If you have already removed old migrations, please clean your database and remigrate.Inodorous
A
10

Adding to terry_brown's answer, this is what cause my problems. I had a custom user model with ForeignKey to another model. And I set defaults to first object in the DB. It worked when I had the data in the database. But when I started from scratch, it didn't work because it was executed immediately when imported (so not even migration went through).

class User(AbstractBaseUser, PermissionsMixin):
    subscription_plan = models.ForeignKey(SubscriptionPlan, default=SubscriptionPlan.objects.first().id)

I had to sacrifice that default (commenting it out).

UPDATE: A better solution would be to prepopulate your database with initial migration or fixtures.

Askari answered 5/12, 2016 at 15:50 Comment(1)
Same problem here. In my case, I had a class that tried to access the DB in its constructor.Once
B
6

Follow this steps to get fixed this issue.

python manage.py migrate --fake APPNAME zero

This will make your migration to fake. Now you can run the migrate script

python manage.py migrate APPNAME

OR

python manage.py migrate

Tables will be created and you solved your problem.. Cheers!!!

Bipetalous answered 17/2, 2020 at 20:49 Comment(1)
This worked for me, but slightly different: I did the fake migration to zero, and then migrated the app, and finally did an additional fake migration. migrate --fake APP zero migrate APP, migrate --fakeRamiroramjet
C
3

I read the above Answers given by other teams. Majorly were asking to delete SQLite(DB) and reset the "migrations" folder.

If you are working in a production environment then this will not be the right choice.

  1. python manage.py migrate --fake APPNAME zero
  2. python manage.py migrate APPNAME
  3. python manage.py makemigrations APPNAME
  4. python manage.py migrate APPNAME

These four steps are enough to solve this issue.

Churchwell answered 7/3, 2020 at 5:42 Comment(1)
The first step didn't workedQuagga
H
3

I faced the same problem. I removed all migrations and run this command

python manage.py makemigrations
python manage.py migrate --run-syncdb

It worked for me and the data was also safe (I didn't lose any)

Heraclitus answered 20/4, 2022 at 3:4 Comment(1)
The second line created non existed table, even though the corresponding class was defined. Worked for me, thanks.Strappado
M
2

This error is happening because of the database of Django , this is not user fault. Its easiest solution is create new app with different name .Then create same models and then run python manage.py makemigrations and then migrate. By doing this your error should be solved

Mayfair answered 27/4, 2021 at 12:33 Comment(0)
F
2

Maybe migrations Folder was not created:

python manage.py makemigrations app_name
python manage.py migrate 
Furlana answered 15/9, 2022 at 8:32 Comment(1)
This saved the day. Thanks.Moffatt
S
1

While running any management command "django.contrib.admin" automatically attempts to discover and admin.py modules in installed apps.

If there is a code related to database, it runs automatically and tries to load data from database when it can not find data related table in database throw this Error.

To fix this error just change "django.contrib.admin" in INSTALLED_APPS to "django.contrib.admin.apps.SimpleAdminConfig", it will prevent "django.contrib.admin" from auto discovering and running admin modules.

django.contrib.admin automatically performs auto discovery of admin modules in installed applications. To prevent it, change your INSTALLED_APPS to contain 'django.contrib.admin.apps.SimpleAdminConfig' instead of 'django.contrib.admin'.

https://docs.djangoproject.com/en/3.0/ref/applications/#troubleshooting

Stigma answered 4/12, 2019 at 12:38 Comment(1)
None of the other answers except this address the issue when a code inside admin.py tries to look out for some values data and causes an error. But this takes away the rights of superuser to even view the models from the admin.Gullett
U
1

You don't need views to makemigrations. Comment out all references to other apps from urls.py, clear db and old migrations, run makemigrations, and comment your urls.py back in. Worked for me.

Underslung answered 23/2, 2020 at 9:13 Comment(1)
this is the only solution that worked for me. was abe to solve after like 4 hours of trouble shooting +1 for you mateMargaretamargarete
M
1

I had the same problem. None of the above solutions worked for me. It all probably started when I added a new model, had a few objects in the database and then I changed model's name. I needed to delete the whole model from my app and then run app's admin page. Then I restored the model by clicking ctrl + z in all files from which I deleted it and finally I was able to run makemigrations and migrate commands.

Matriarchate answered 13/4, 2020 at 7:41 Comment(0)
B
1

I was facing the same error. The steps I used to solve this issue is:

  1. Make sure that there's migrations folder inside your app. If there isn't any, create the migrations folder inside the app folder, and then create __init__.py file inside the folder.

  2. If the migrations folder is already there, then delete all the migration files.

  3. Delete the database file which is by default db.sqlite3.

  4. Run the command python manage.py makemigrations

  5. python manage.py migrate

Bespoke answered 14/8, 2020 at 10:19 Comment(0)
P
0

Maybe out of time but...I have same problem when I tried to "clone" Django 1.11 installation into other directory and then with initial try to manage makemigrations.

I solve the problem following way:

  1. settup initial Django installation and creating main application by:

django-admin.py startproject app_name

  1. initial migrations manage makemigrations, manage migrate

  2. Setup the superuser:

manage createsuperuser

  1. copy all files and directories (Django applications) except the urls.py and settings.py in main directory

  2. Added all apps into INSTALLED_APPS

  3. manage makemigrations, manage migrate

  4. Copied settings.py and urls.py from source Django application directory

Thats it no errors and all is working fine.

Petr

Peng answered 18/10, 2018 at 14:57 Comment(0)
T
0

If someone else has this problem and the accepted solution is not working, have a look at your db path, the db path should be absolute path, 'NAME': '/pathto-db/default.db',

Link

Tallith answered 4/11, 2018 at 10:41 Comment(0)
Q
0

If none of the above solution worked for you then add the appname along with the makemigration and migrate command.

 makemigration login
 migrate login

That might help you to figure out the problem.

Quartzite answered 9/1, 2020 at 19:35 Comment(0)
B
0

I got this error while creating a model. I opened the db.sqlite3 file and created a table for the model using SQLite DB Browser. Then I created a migration and fake migrated it. Don't know what caused the issue but this workaround helped.

Bunnybunow answered 4/4, 2020 at 14:18 Comment(0)
T
0

would you delete a production bank? I saw that many have the sqlite deleted, but if it is a production bank?

solution to delete data from django_migrations table less contenttypes

already in the table django_content_type you remotely app_label

inside the migrations folder deletes everything but init.py

python manage.py makemigrations

python manage.py migrate --fake

that's how I solved the app duplication problems (I had two apps with the same name after installing a plugin) and django created the missing tables, among other things.

in my normally functional case

Tandratandy answered 23/5, 2020 at 19:8 Comment(0)
E
0

With same error and without removing database:

  • remove migrations
  • remove __pychache__
  • python manage.py makemigrations --empty alias
  • python manage.py makemigrations alias
  • python manage.py migrate alias zero
  • remove again migrations
  • remove again __pycache__
  • python manage.py makemigrations
  • python manage.py migrate alias zero

Where alias is the app name.

Eisler answered 4/12, 2020 at 14:8 Comment(0)
W
0

If you have deleted the DB and migrating now this will happens.

For eg if your error says no such table table1 then

  • python manage.py makemigrations
  • python manage.py migrate
  • python manage.py table1 app1

Here table1 is the name of the table and app1 is the Django app name where the table1 model exists.

Weigel answered 21/12, 2020 at 18:25 Comment(0)
D
0

I know this commonly solved by deleting de sqlite3 DB that is used in the development process.

Also, I know this question is currently solved, but I want to leave my case here as an alternative.

Sometimes while we are programming we change a lot of things in our models. When we run python manage.py makemigrations a file is created inside of our app folder/migrations. And when we run python manage.py migrate a record in the table django_migrations is created. this record contains 3 fields we must check in detail:

  • 1 - name (this is the file name created in the migrations app folder)
  • 2 - app (this is the name of our app. Also works like a namespace to prevent conflicts)
  • 3 - applied (this is the date-time when the migration was executed).

If you've modified your model previously, you should have several files inside migrations (amount accordingly with the times you've executed makemigrations on every change), in my case I wanted to erase these files just to have only one migration file.

The problem with this is that when makemigrations was run again it creates a file 0001_initial.py. If you remember the table django_migrations contains a log of this file, this is to prevent the execution of migrations that already have been done.

If this is your case, you would erase the records of your app migrations from this table.

Dunstable answered 20/6, 2021 at 6:5 Comment(0)
D
0

I did some alterations in my database and was facing the same issue. None of solutions worked for me so after spending hours i finally decided to delete the "db.sqlite3" file and runs the makemigrations and migrate commands. After it worked fine. But this solution is not a good one to use immediately, use it only when you are out of options.

Depreciate answered 24/12, 2021 at 22:1 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Bandage
C
0

I recently had a problem with this and used the @adam post to resolve my issue. I just wanted to amend his post and say that, for me in windows 10 using git bash, I had to do all of this from the venv, and then after I removed the migration files and the DB I had to pip uninstall django and pip install django before making the migrations.

Cystectomy answered 11/11, 2022 at 14:37 Comment(0)
U
0

This issue comes up for me when I have a function/class/etc. somewhere that uses fields from the Database -- typically when using Django's Form classes.

Example:

brands = forms.MultipleChoiceField(
        choices=[(b.name, b.id) for b in Brand.objects.all()],
        widget=forms.CheckboxSelectMultiple()
    )

Here I'm creating a MultipleChoiceField entry for a form using the name and id fields from all brand object entries in a database. i.e. loading all the options a user can select in the database from the database.

When the database is already present and the app_brand table is already present, there is no issue.

However, when creating migrations for this application initially, I get the Error:

django.db.utils.OperationalError: no such table: app_brand

I don't have an elegant work-around, but what I usually do is the following:

# default brands
try:
    brands = forms.MultipleChoiceField(
        choices=[(b.name, b.id) for b in Brand.objects.all()],
        widget=forms.CheckboxSelectMultiple()
    )
except Exception as e:
    brands = forms.MultipleChoiceField(
        choices=[],
        widget=forms.CheckboxSelectMultiple()
    )

This allows the initial python manage.py makemigrations command to be issued w/o raising the exception. The obvious downside is that there are likely cases that would normally cause the application to fail that might now simply result in an unpopulated form field in a production environment.

TL;DR - It's an issue sometimes if an application has functions/etc. that access the database such as Forms and those database tables don't already exist.

Unblushing answered 5/1, 2023 at 17:6 Comment(0)
D
0

I had similar issues, cannot make migrations in no present database etc.. disabling forms import in view works, Importing form code to view works too, but this is solution:

I added model = super().__class__() in each init function in model form class:

def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        model = super().__class__()    # 'soft code' prevents operational error
        self.fields['name'].required = False   

And also I need to modify checkbox list:

  # CATEG_CHOICES= Category.choices_objects.all()
  # CATEG_CHOICES=Category.objects.values_list('id','name')  # without ..
   
  choice_list = []
    try:
        choice_list.extend(Category.choices_objects.all())
        # choice_list.extend(Category.objects.values_list('id','name'))
    except OperationalError:
        pass  # happens when db doesn't exist yet
         
    CATEG_CHOICES=choice_list
Dynel answered 14/3, 2023 at 10:57 Comment(0)
E
-1

The only way to fix my error was commenting out every single file. This error might occur while a file thinks the database is not empty, or that it actually exists.

I just commented out the entire project, migrated, uncommented the models.py file, migrated again, uncommented the entire project. I have no idea why it worked.

Espy answered 5/11, 2020 at 21:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.