I have a Django 1.5 application running on apache2 server and using sqlite database.
The setting for the database is as follow
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '/var/www/html/project/devdb',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
where devdb is the database file generated.
When I run migration commands from the terminal console, it works fine and data is migrated to the database.
But when I visit the application URL, it gives the error
DatabaseError at /url_path/
attempt to write a readonly database
Then I change the permission of file using
sudo chown 777 devdb
Then it starts giving the error
DatabaseError at /url_path/
unable to open database file
ls -la gives following output for the devdb file
-rwxr-xr-x 1 ubuntu ubuntu 1036 May 11 2018 manage.py
-rw-rw-r-- 1 ubuntu ubuntu 291840 May 28 09:31 devdb
Getting user of the apache2 running using
ps -ef | egrep '(httpd|apache2|apache)' | grep -v `whoami` | grep -v root | head -n1 | awk '{print $1}'
gives www-data
But changing owner of the file to www-data again gives unable to open database file.
A sqlite db needs to be owned by www-data and so does the directory it is in.
So if your app is in /var/www/app do
cd /var/www
chown www-data:www-data app
cd app
chown ww-data:www-data devdb
Related
I am working on connecting a Postgres DB to Django. I have created the db through pgAdmin 4 under the user postgres. I've set my environment variables as followed
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
try:
if sys.argv[1:2] != ['test']:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'HOST': env('PGHOST'),
'USER': env('PGUSER'),
'NAME': env('PGDATABASE'),
'PASSWORD': env('PGPASSFILE'),
'PORT': env('PGPORT'),
}
}
except:
pass
with my .env file containing each variable. When I try to migrate it through ubuntu command line I get the error database <dbname> does not exist I've installed psycopg2 and pillow and set local all postgres peer to local all postgres md5. my os is windows 11 so I am wondering if this is happening because my project directory is through ~/directory/to/path and postgres and pgAdmin are installed in /etc/postgresql/ and /mnt/c/'Program Files'/PostgreSQL? Should I move those files from / to ~?
NOTE: I've run psql canvasDB and got back role "awilbur" does not exist
If you installed postgresql through an installer (which I assume is the way since you're on Windows), you might've remembered that the installer asked you for a password. If you do remember, you should try:
me#My-MacBook-Pro ~ [2]> psql -U postgres
Password for user postgres:
psql (14.2, server 14.1)
Type "help" for help.
postgres=# CREATE DATABASE test;
CREATE DATABASE
Specifying -U postgres will log you into the default user, whose default password is the password you entered into the installer.
If you don't, you could try this: go to the Control Panel -> Administrative Tools -> Computer Management. Under "Local Users and Groups" you can see all users created for your system. Remove "postgres" and reinstall PostgreSQL.
After you're done, you can verify by:
postgres=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+---------+-------+-----------------------
postgres | postgres | UTF8 | C | C |
template0 | postgres | UTF8 | C | C | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | C | C | =c/postgres +
| | | | | postgres=CTc/postgres
test | postgres | UTF8 | C | C |
(5 rows)
I want to use a better database with my Django like postgresql or mysql. what are the steps in doing that?
In case of MySQL:
Install mysqlclient in your virtualenv.
$ pip install mysqlclient
Enter MySQL and Create database to connect your project
$ mysql
mysql> create database django_project;
Query OK, 1 row affected (0.01 sec)
mysql> use django_project
mysql> show tables;
Empty set (0.01 sec)
Connect your project to database(MySQL)
# your_settings.py
...
DATABASES = {
'default' : {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django_project',
'USER': 'root',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '3306',
}
}
Migrate
$ python manage.py migrate
Check
$ mysql
mysql> use django_project;
mysql> show tables;
+--------------------------+
| Tables_in_django_project |
+--------------------------+
| accounts |
| comments |
| django_content_type |
| django_migrations |
| django_session |
+--------------------------+
5 rows in set (0.01 sec)
Done!
TL;DR manage migrate fails but manage dbshell works.
This is a dockerized dev environment on OSX10.6, boot2docker with django 1.8.4 and postgresql 9.4.4.
/manage.py migrate throws:
django.db.utils.OperationalError: FATAL: password authentication failed for user "xxxxx"
but here's the bit that confuses me, django dbshell works, copy and pasting the password out of the environment variable
root#df6501ab7341:/src/web# ./manage.py dbshell
Password for user xxxxx:
psql (9.4.4)
Type "help" for help.
xxxxx=# \du
List of roles
Role name | Attributes | Member of
--------------+------------------------------------------------+-----------
xxxxx | Superuser +| {}
| Password valid until infinity |
mpasysuser01 | | {}
postgres | Superuser, Create role, Create DB, Replication | {}
xxxxx=#
Django settings are:
# Database Configuration
DATABASES = {
'default': {
'ENGINE' : 'django.db.backends.postgresql_psycopg2',
'NAME' : os.environ.get('DATABASE_ENV_POSTGRES_USER' , ''), # the database name is the same as the dbo username
#ToDo Use unprivileged database user
# 'USER' : os.environ.get('DATABASE_ENV_UNPRIVILEGED_SQL_USER', ''),
'USER' : os.environ.get('DATABASE_ENV_POSTGRES_USER', ''),
'PASSWORD' : os.environ.get('DATABASE_ENV_POSTGRES_PASSWORD', ''),
'HOST' : os.environ.get('DATABASE_PORT_5432_TCP_ADDR' , ''),
'PORT' : os.environ.get('DATABASE_PORT_5432_TCP_PORT' , ''),
},
}
and the database logs show:
database_1 | FATAL: password authentication failed for user "xxxxx"
database_1 | DETAIL: Connection matched pg_hba.conf line 95: "host all all 0.0.0.0/0 md5"
I second what #larconda said.
I was racking my brain and decided to print by:
Open the shell
import os
print(your variable here)
That should provide some input - it turned out to be a missing space for me.
I switched to my database engine to PostGIS and now I'm switching back to PostgreSQL (so I can continue to use Heroku for free). I changed my settings.py file back to:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'chishenma',
'HOST': 'localhost',
}
}
and commented out the installed app so now it shows:
# 'django.contrib.gis',
First I made sure that Postgres.app is running. Then I deleted my migrations, ran python manage.py syncdb, and did the South migrations again, all without errors. When I go into the psql shell and type \l, I can see my database, "chishenma," in the list:
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-------------------------+-----------------+----------+-------------+-------------+----------------------
chishenma | michelleglauser | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
However, when I type \d, I get "No relations found." I tried to re-create the database, but I get "ERROR: Database chishenma already exists."
I looked at this and this Stack Overflow thread and determined that my access privileges (I've got the "=UC/postgres" part) and search_path are correct. I get:
List of schemas
Name | Owner | Access privileges | Description
--------+-----------------+------------------------------------+------------------------
public | michelleglauser | michelleglauser=UC/michelleglauser+| standard public schema
| | =UC/michelleglauser
and:
List of roles
Role name | Attributes | Member of
-----------------+------------------------------------------------+-----------
michelleglauser | Superuser, Create role, Create DB, Replication | {}
What am I missing? How do I make the relations findable?
I installed prostgres to use with my rails4 app, and I am able to connect to the database server and create databases. Then I made the necessary changes to my Gemfile and config/database.yml to use postgres. Then I created a new app, and in the app I created a User model:
$ rails generate model User name:string email:string
invoke active_record
create db/migrate/20130806145935_create_users.rb
create app/models/user.rb
invoke rspec
create spec/models/user_spec.rb
And then I did:
$ bundle exec rake db:migrate
== CreateUsers: migrating ====================================================
-- create_table(:users)
-> 0.1498s
== CreateUsers: migrated (0.1500s) ===========================================
But in the db directory, I see these files:
development.sqlite3
test.sqlite3
Furthermore, when I try to look at those files with the SQLite Database Browser, I get an error that says they are not sqlite 3 databases. In fact, they are empty:
~/rails_projects/sample_app4_0/db$ ls -al
total 40
drwxr-xr-x 8 7stud staff 272 Aug 6 22:50 .
drwxr-xr-x 24 7stud staff 816 Aug 6 22:23 ..
-rw-r--r-- 1 7stud staff 0 Jul 30 00:21 development.sqlite3
drwxr-xr-x 3 7stud staff 102 Aug 6 22:22 migrate
-rw-r--r-- 1 7stud staff 1063 Aug 6 09:06 schema.rb
-rw-r--r-- 1 7stud staff 343 Jul 29 20:01 seeds.rb
-rw-r--r-- 1 7stud staff 0 Jul 30 03:02 test.sqlite3
I read that you can create your rails app with a flag that tells it to use postgres:
rails new myapp --database postgresql
but I already created my app. Do I have to start over? I'm using git if that makes a difference.
My Gemfile:
source 'https://rubygems.org'
ruby '2.0.0'
#ruby-gemset=railstutorial_rails_4_0
gem 'rails', '4.0.0'
gem 'bootstrap-sass', '2.3.2.0'
#Added for postgres:
gem 'pg', '0.15.1'
group :development, :test do
#gem 'sqlite3', '1.3.7'
gem 'rspec-rails', '2.13.1'
gem 'guard-rspec', '2.5.0'
gem 'spork-rails', github: 'sporkrb/spork-rails'
gem 'guard-spork', '1.5.0'
gem 'childprocess', '0.3.6'
end
group :test do
gem 'selenium-webdriver', '2.0.0'
gem 'capybara', '2.1.0'
gem 'growl', '1.0.3'
end
gem 'sass-rails', '4.0.0'
gem 'uglifier', '2.1.1'
gem 'coffee-rails', '4.0.0'
gem 'jquery-rails', '2.2.1'
gem 'turbolinks', '1.1.1'
gem 'jbuilder', '1.0.2'
group :doc do
gem 'sdoc', '0.3.20', require: false
end
group :production do
#gem 'pg', '0.15.1'
gem 'rails_12factor', '0.0.2'
end
config/database.yml:
development:
adapter: postgresql
encoding: utf8
database: sampleapp_dev #can be anything unique
pool: 5
timeout: 5000
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: postgresql
encoding: utf8
database: sampleapp_test #can be anything unique
pool: 5
timeout: 5000
production:
adapter: postgresql
database: sampleapp_prod
pool: 5
timeout: 5000
Okay, to figure out what's going on I created a new test app using the --database flag:
rails_projects$ rails new test_postgres --database postgresql
It turns out, all that does is set up your config/database.yml file like this:
development:
adapter: postgresql
encoding: unicode
database: test_postgres_development
pool: 5
username: test_postgres
password:
test:
adapter: postgresql
encoding: unicode
database: test_postgres_test
pool: 5
username: test_postgres
password:
production:
adapter: postgresql
encoding: unicode
database: test_postgres_production
pool: 5
username: test_postgres
password:
And the empty sqlite files:
development.sqlite3
test.sqlite3
were still present in the db directory.
Then I started up postgres, and I used pgAdmin3 to connect to the postgres database server. (If that is confusing, see: How do I start enterpiseDB PostgreSQL on Mac OSX 10.6.8?)
Then I created a model:
~/rails_projects$ cd test_postgres/
~/rails_projects/test_postgres$ rails g scaffold Post title:string author:string body:text
invoke active_record
create db/migrate/20130807061320_create_posts.rb
create app/models/post.rb
invoke test_unit
create test/models/post_test.rb
create test/fixtures/posts.yml
invoke resource_route
route resources :posts
invoke scaffold_controller
create app/controllers/posts_controller.rb
invoke erb
create app/views/posts
create app/views/posts/index.html.erb
create app/views/posts/edit.html.erb
create app/views/posts/show.html.erb
create app/views/posts/new.html.erb
create app/views/posts/_form.html.erb
invoke test_unit
create test/controllers/posts_controller_test.rb
invoke helper
create app/helpers/posts_helper.rb
invoke test_unit
create test/helpers/posts_helper_test.rb
invoke jbuilder
create app/views/posts/index.json.jbuilder
create app/views/posts/show.json.jbuilder
invoke assets
invoke coffee
create app/assets/javascripts/posts.js.coffee
invoke scss
create app/assets/stylesheets/posts.css.scss
invoke scss
create app/assets/stylesheets/scaffolds.css.scss
Then I tried to execute the migration:
~/rails_projects/test_postgres$ bundle exec rake db:migrate
rake aborted!
FATAL: role "test_postgres" does not exist
...
...
That error occured because I don't have a database user(or role in postgres speak) named test_postgres--and it's likely no one else will either. When I set up postgres, I created the user 7stud, which is my Mac user name. To fix that rails error, I just changed the username to 7stud on the three lines in config/database.yml. Edit: in fact, I didn't even need to do that. Because I am the user 7stud on my Mac, that means I am executing my rails commands as 7stud, and coupled with the fact that my postgres db was setup with a user named 7stud, that allows me to completely eliminate the username line in config/database.yml:
development:
adapter: postgresql
encoding: unicode
database: test_postgres_development
pool: 5
test:
adapter: postgresql
encoding: unicode
database: test_postgres_test
pool: 5
production:
adapter: postgresql
encoding: unicode
database: test_postgres_production
pool: 5
Then I tried executing the migration again:
~/rails_projects/test_postgres$ bundle exec rake db:migrate
rake aborted!
FATAL: database "test_postgres_development" does not exist
...
...
Notice that the database.yml file specifies three database names. So I created the development and test databases:
~$ cd /Library/PostgreSQL/9.2/
/Library/PostgreSQL/9.2$ sudo su postgres
Password: <normal sudo password>
bash-3.2$ createdb -O7stud -Eutf8 test_postgres_development
bash-3.2$ createdb -O7stud -Eutf8 test_postgres_test
-O owner
-E encoding
Then I tried executing the migration again:
~/rails_projects/test_postgres$ bundle exec rake db:migrate
== CreatePosts: migrating ====================================================
-- create_table(:posts)
-> 0.0441s
== CreatePosts: migrated (0.0443s) ===========================================
Success (but elsewhere on the net examples show different output with 'Notice' lines).
Then I started a server:
~/rails_projects/test_postgres$ rails s
...and in my browser I entered the url:
http://localhost:3000/posts
...and I created a couple of Posts.
Then using pgAdmin3, I tried to find the posts in the test_postgres_development database. First, I refreshed the 'Databases(3)' line in pgAdmin3 by right clicking on the line and choosing 'Refresh'. Then I searched through the test_postgres_development directory for a long time, with no luck. Under Schemas, I could see a Tables directory that contained a posts directory, so the table got created, but I couldn't figure out how to see if there were any entries in the table. It turns out, you have to right click on the posts directory, then select 'View Data', and voila there were the posts I created.
Or you can view the entries using the command line:
~$ cd /Library/PostgreSQL/9.2/
/Library/PostgreSQL/9.2$ sudo su postgres
Password: <normal sudo password>
bash-3.2$ psql -U 7stud test_postgres_development
psql (9.2.4)
Type "help" for help.
test_postgres_development=> \dt
List of relations
Schema | Name | Type | Owner
--------+-------------------+-------+-------
public | posts | table | 7stud
public | schema_migrations | table | 7stud
(2 rows)
test_postgres_development=> \d posts
Table "public.posts"
Column | Type | Modifiers
------------+-----------------------------+----------------------------------------------------
id | integer | not null default nextval('posts_id_seq'::regclass)
title | character varying(255) |
author | character varying(255) |
body | text |
created_at | timestamp without time zone |
updated_at | timestamp without time zone |
Indexes:
"posts_pkey" PRIMARY KEY, btree (id)
test_postgres_development=> select id, title, author, created_at from posts;
id | title | author | created_at
----+------------------------+--------------+----------------------------
1 | Hi there. | Tom | 2013-08-07 06:24:57.806237
2 | Ola! | Nancy | 2013-08-07 06:25:23.989643
(2 rows)
test_postgres_development=>