问题
In Django, I've added some models into models.py
. After manage.py makemigrations
, manage.py migrate
raised this exception:
django.db.utils.OperationalError: no such table: auth_test_usertranslatorprofile
So I've removed all old migrations and run makemigrations
and migrate
again which seemed to work.
Unfortunately, I've noticed that it didn't helped because when I try to click on User customer profiles
of User translator profiles
it raises exception:
Environment:
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
I'm attaching my files:
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'))
Do you know where is the problem? Thanks
回答1:
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
I hope this helps.
回答2:
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
回答3:
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.
回答4:
run below command. It solves me once this issue
manage.py migrate --run-syncdb
回答5:
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:
- settup initial Django installation and creating main application by:
django-admin.py startproject app_name
initial migrations manage makemigrations, manage migrate
Setup the superuser:
manage createsuperuser
copy all files and directories (Django applications) except the urls.py and settings.py in main directory
Added all apps into INSTALLED_APPS
manage makemigrations, manage migrate
Copied settings.py and urls.py from source Django application directory
Thats it no errors and all is working fine.
Petr
回答6:
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
回答7:
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
来源:https://stackoverflow.com/questions/34548768/django-no-such-table-exception