简体   繁体   中英

OperationError on first query to django sqlite3 database

The beginning of my settings.py has the following.

import os, sys

PROJECT_PATH            = os.path.dirname(os.path.abspath(__file__))
CURRENT_DIR             = os.path.dirname(__file__)
TEMPLATE_DIRS           = (os.path.join(CURRENT_DIR, 'templates'),)
STATICFILES_DIRS        = (os.path.join(CURRENT_DIR, 'static'),)

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
  # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.sqlite3', 
    'NAME': '/home/ubuntu/myapp/myapp',       
  }
}

I get the following in my error log after a call from views.py to the database.

[time] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 372, in count
[time] [error]     return self.query.get_count(using=self.db)
[time] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 423, in get_count
[time] [error]     number = obj.get_aggregation(using=using)[None]
[time] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 389, in get_aggregation
[time] [error]     result = query.get_compiler(using).execute_sql(SINGLE)
[time] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 839, in execute_sql
[time] [error]     cursor = self.connection.cursor()
[time] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py", line 324, in cursor
[time] [error]     cursor = self.make_debug_cursor(self._cursor())
[time] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py", line 306, in _cursor
[time] [error]     self._sqlite_create_connection()
[time] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py", line 296, in _sqlite_create_connection
[time] [error]     self.connection = Database.connect(**kwargs)
[time] [error] OperationalError: unable to open database file

How do I go about correctly referring to my database file in settings.py ?

'NAME': '/home/ubuntu/myapp/myapp' looks to me like you're referring to a folder instead of a file. For SQLite, the database name must be a full path, including the name of a file, so, as you already got your project's folder programmatically, you could use that to construct the file path:

'NAME': os.path.join(PROJECT_PATH, 'mydb.db')

您需要运行python manage.py syncdb ,因为该过程将创建数据库,然后才能在views.py或其他任何地方访问它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM