Operational error no such table

Ответили на вопрос 1 человек. Оцените лучшие ответы! И подпишитесь на вопрос, чтобы узнавать о появлении новых ответов.

При выполнении manage.py makemigrations появляется ошибка о том, что таблица (на которую надо сделать миграцию) не существует:

Список вызовов

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "D:enviropmentsNewElionlibsite-packagesdjangocoremanagement__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "D:enviropmentsNewElionlibsite-packagesdjangocoremanagement__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "D:enviropmentsNewElionlibsite-packagesdjangocoremanagementbase.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "D:enviropmentsNewElionlibsite-packagesdjangocoremanagementbase.py", line 342, in execute
    self.check()
  File "D:enviropmentsNewElionlibsite-packagesdjangocoremanagementbase.py", line 374, in check
    include_deployment_checks=include_deployment_checks,
  File "D:enviropmentsNewElionlibsite-packagesdjangocoremanagementbase.py", line 361, in _run_checks
    return checks.run_checks(**kwargs)
  File "D:enviropmentsNewElionlibsite-packagesdjangocorechecksregistry.py", line 81, in run_checks
    new_errors = check(app_configs=app_configs)
  File "D:enviropmentsNewElionlibsite-packagesdjangocorechecksurls.py", line 14, in check_url_config
    return check_resolver(resolver)
  File "D:enviropmentsNewElionlibsite-packagesdjangocorechecksurls.py", line 24, in check_resolver
    for pattern in resolver.url_patterns:
  File "D:enviropmentsNewElionlibsite-packagesdjangoutilsfunctional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "D:enviropmentsNewElionlibsite-packagesdjangourlsresolvers.py", line 313, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "D:enviropmentsNewElionlibsite-packagesdjangoutilsfunctional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "D:enviropmentsNewElionlibsite-packagesdjangourlsresolvers.py", line 306, in urlconf_module
    return import_module(self.urlconf_name)
  File "D:Python27Libimportlib__init__.py", line 37, in import_module
    __import__(name)
  File "D:YandexDiskWORK!Projects DjangotestElionElionurls.py", line 5, in <module>
    from about import views as about_views
  File "D:YandexDiskWORK!Projects DjangotestElionaboutviews.py", line 6, in <module>
    from .forms import ContactMessageForm, SubmitApplication
  File "D:YandexDiskWORK!Projects DjangotestElionaboutforms.py", line 42, in <module>
    class SubmitApplication(forms.Form):
  File "D:YandexDiskWORK!Projects DjangotestElionaboutforms.py", line 43, in SubmitApplication
    regions = [(obj.id, obj.region) for obj in AreasWork.objects.all()]
  File "D:enviropmentsNewElionlibsite-packagesdjangodbmodelsquery.py", line 256, in __iter__
    self._fetch_all()
  File "D:enviropmentsNewElionlibsite-packagesdjangodbmodelsquery.py", line 1087, in _fetch_all
    self._result_cache = list(self.iterator())
  File "D:enviropmentsNewElionlibsite-packagesdjangodbmodelsquery.py", line 54, in __iter__
    results = compiler.execute_sql()
  File "D:enviropmentsNewElionlibsite-packagesdjangodbmodelssqlcompiler.py", line 835, in execute_sql
    cursor.execute(sql, params)
  File "D:enviropmentsNewElionlibsite-packagesdjangodbbackendsutils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "D:enviropmentsNewElionlibsite-packagesdjangodbbackendsutils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "D:enviropmentsNewElionlibsite-packagesdjangodbutils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "D:enviropmentsNewElionlibsite-packagesdjangodbbackendsutils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "D:enviropmentsNewElionlibsite-packagesdjangodbbackendssqlite3base.py", line 337, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: AreasWork

В этом списке вызовов показано, что вызывается forms.py этого приложения в том месте где есть обращение к данной таблице:

# Elionaboutforms.py:
class SubmitApplication(forms.Form):
    regions = [(obj.id, obj.region) for obj in AreasWork.objects.all()] # Ошибка в этой строке
    choice_region = [(None, 'Выберите город')] + regions + [('0', 'Другой')]
    region = forms.ChoiceField(label='Область', choices=choice_region,
                               widget=forms.Select(attrs={'class': 'form-control'}))
    ............

Если в этом месте убрать обращение к БД, то ошибок больше никаких не появляется. Даже после выполнения manage.py migrate и в forms.py вернуть код обратно, то всё будет работать нормально, без ошибок.

Также, я нашёл, что у кого-то была аналогичная проблема и тоже ошибка в файле forms.py при обращении к БД.

Понятно, что для решения проблемы, надо тупо убрать обращение к БД в форме, но мне интересно, почему вообще такое происходит и что я делаю не правильно?


Recommended Answers

All 4 Replies


rproffitt

2,383



«Nothing to see here.»



Moderator


5 Years Ago

Edited

5 Years Ago
by rproffitt because:

Spelling

Member Avatar


cereal

1,524



Nearly a Senior Poster



Featured Poster


5 Years Ago

Hi!

In addition to previous suggestion: if the path is wrong or does not have write permissions Python would return:

sqlite3.OperationalError: unable to open database file

Instead you get:

sqlite3.OperationalError: no such table: Airports

Which can be generated if:

  1. the database file name is wrong due, for example, to the case: linux is case sensitive, Mac OS no (at least not by default)
  2. the database file or the parent directory is read-only, so you have to change the permissions
  3. the table does not exists

In the first case connect() will create the database file, but this obviously won’t have the Airports table.

In the first case this:

for row in cur.execute('''SELECT "Hello"'''):
    print row

will run successfully, it will run successfully also if the file is read-only, but it will fail if there are permission issues with the parent directory. The error, however, will be related to the database file, not to the table.

Edited

5 Years Ago
by cereal

Member Avatar

5 Years Ago

rproffitt, well — capitalization may be important in postgress but not in sqlite. In this case our vendor spelled table «Airports» as «Airports» but in a terminal «aIrPoRtS» will do just fine if one is so inclined.

cereal, the path is correct. To be sure I copied it from a file manager. The permissions of directory and file are set correctly as well. The table exists — I’ve been working with it in a terminal while trying to make this python script.

Meanwhile I did some editing and the new version works fine:

#!/usr/bin/python
import sqlite3

datafile = 'XZ704.DB'
datadir = '/full_path_to/SQLITE_FILES/'
datadir = '../SQLITE_FILES/'
db = datadir+datafile

conn = sqlite3.connect(db)
conn.text_factory = sqlite3.OptimizedUnicode
cur = conn.cursor()

for row in cur.execute('SELECT Ident FROM Airports'):
    print row

conn.close()

Why overwriting the the first content of «datadir» made a difference…???
conn.text_factory = sqlite3.OptimizedUnicode was inserted after the script started working.

For now I consider my problem solved — but I’m still puzzled.

Thanks!


rproffitt

2,383




«Nothing to see here.»



Moderator


5 Years Ago

Why overwriting the the first content of «datadir» made a difference…?

Sounds like file permissions or rights issues to me. Your app runs as some user and the overwrite creates the file with the rights of the app and its context.

I find this most often happens under Windows. Linux, not so much. What was the host OS?


Reply to this topic

Be a part of the DaniWeb community

We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.

Hello Miguel, I’ve finished your book and tried to build a «notebook» project without the help of the book. «Notebook» is a simplified flasky, no User, no Role, no Migrate, No Manage, just Post.

I thought it would be easy, and everything went well until I added these two lines in views.py:
posts = Post.query.order_by(Post.timestamp.desc()).all() return render_template('index.html', current_time = datetime.utcnow(), form = form, posts = posts)
I got the following error:
sqlalchemy.exc.OperationalError: (OperationalError) no such table

I read issue #18, but still can’t solve my problem(I didn’t use manager to modify the command line).
Could you please tell me what’s wrong with it?
Thank you !!

Here’s my code:

run.py

# -*- coding:utf-8 -*-
from app import create_app
app = create_app()
if  __name__ == '__main__':
     app.run(debug = True)

init.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy 
from flask_moment import Moment
from flask_bootstrap import Bootstrap


moment = Moment ()
bootstrap = Bootstrap()
db = SQLAlchemy()

def create_app():
    app = Flask(__name__)
    moment.init_app(app)
    bootstrap.init_app(app)
    app.secret_key = 'SECRET_KEY'
    db.init_app(app)
    with app.app_context():
           db.create_all()

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    return app

views.py

from flask import render_template, redirect, url_for, session
from datetime import datetime
from . import main
from app.forms import PostForm
from flask_login import current_user
from ..models import Post


@main.route('/', methods = ['GET', 'POST'])
def index():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(body = form.body.data)
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('.index'))
    posts = Post.query.order_by(Post.timestamp.desc()).all()
    return render_template('index.html', current_time = datetime.utcnow(), form = form, posts = posts)

@main.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Operation terminated with error 1216
  • Operation terminated with error 1023
  • Operation terminated with error 1003
  • Operation progress details completed with fatal error s 0
  • Operation generated oracle error 31626

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии