Heroku Django db postgres error - python

I am trying to get my first django app up, but I'm running into this db error:
OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" and accepting
TCP/IP connections on port 5432?
This happens whenever I try to syncdb, migrate, or createsuperuser
I am configuring my DATABASES variable like:
DATABASES = {'default' : dj_database_url.config(default=os.environ["HEROKU_POSTGRESQL_OLIVE_URL"]) }
Is there something else I need to configure or am doing wrong?
EDIT (SOLVED):
Thanks for helping me narrow down the problem, I've found the solution.
Since this was the first time I deployed to heroku and the first time I used the two scoops django directory format. I thought doing something like
python manage.py syncdb # would be okay
instead beause my settings folder looks like
.../settings
base.py
local.py
production.py
demo.py
# ...
I need to do
python manage.py syncdb --app.settings.demo

Your syntax seems right, try using DATABASE_URL after verifying you promoted HEROKU_POSTGRESQL_OLIVE_URL, although it should work even when not promoted.
$ heroku pg:promote HEROKU_POSTGRESQL_OLIVE_URL
and then:
import dj_database_url
DATABASES = {
'default': dj_database_url.config(default=os.getenv('DATABASE_URL'))
}
This setup should be working. Else, check that you are working on the right settings file. You can verify this by running:
$ heroku run python manage.py shell
and then:
>>> from django.conf import settings
>>> print settings.DATABASES['default']
and verify result.

I had an error in .gitignore and my local settings were getting set by Heroku by mistake.
This will also cause this error message message.

Related

Deplying Django to Heroku - DisallowedHost Error despite Heroku URL in DJANGO_ALLOWED_HOSTS

I've been at this for hours and need help. Initially I thought it was because I had mistakenly done something small that caused it, so I deleted the app, and created everything - virtual env, heroku app, django projects/apps - fresh.
I get the same error.
I made a cookiecutter django app and deployed it to heroku. Everything goes smoothly until it's time to actually use the site.
When I run heroku open, I get the DisallowedHosts error:
DisallowedHost at /
Invalid HTTP_HOST header: 'MY-NEW-APP.herokuapp.com'. You may need to add 'MY-NEW-APP.herokuapp.com' to ALLOWED_HOSTS.
heroku config shows that DJANGO_ALLOWED_HOSTS=MY-NEW-APP.herokuapp.com. I don't overwrite it in my settings file.
I have import django_heroku and django_heroku.settings(locals()) in my settings file.
DJANGO_SETTINGS_MODULE is correctly set to that file.
What's more, I get a warning about DEBUG=True, when DEBUG=False in my settings file and in the heroku environment.
What am I missing? Are hyphens a bad thing? Should I be using herokuapp.com instead of the full URL?
Solved my own question. I just had to:
heroku config:set DJANGO_ALLOWED_HOSTS=.MY-NEW-APP.COM,MY-NEW-APP.herokuapp.com,.herokuapp.com

Django on Heroku: relation does not exist

I built a Django 1.9 project locally with sqlite3 as my default database. I have an application named Download which defines the DownloadedSongs table in models.py:
models.py
from __future__ import unicode_literals
from django.db import models
class DownloadedSongs(models.Model):
song_name = models.CharField(max_length = 255)
song_artist = models.CharField(max_length = 255)
def __str__(self):
return self.song_name + ' - ' + self.song_artist
Now, in order to deploy my local project to Heroku, I added the following lines at the bottom of my settings.py file:
import dj_database_url
DATABASES['default'] = dj_database_url.config()
My application has a form with a couple of text fields, and on submitting that form, the data gets inserted into the DownloadedSongs table. Now, when I deployed my project on Heroku and tried submitting this form, I got the following error:
Exception Type: ProgrammingError at /download/
Exception Value: relation "Download_downloadedsongs" does not exist
LINE 1: INSERT INTO "Download_downloadedsongs" ("song_name", "song_a...
This is how my requirements.txt file looks like:
beautifulsoup4==4.4.1
cssselect==0.9.1
dj-database-url==0.4.1
dj-static==0.0.6
Django==1.9
django-toolbelt==0.0.1
gunicorn==19.6.0
lxml==3.6.0
psycopg2==2.6.1
requests==2.10.0
static3==0.7.0
Also, I did try to run the following commands as well:
heroku run python manage.py makemigrations
heroku run python manage.py migrate
However, the issue still persists. What seems to be wrong here?
Make sure your local migration folder and content is under git version control.
If not, add, commit & push them as follows (assuming you have a migrations folder under <myapp>, and your git remote is called 'heroku'):
git add <myapp>/migrations/*
git commit -m "Fix Heroku deployment"
git push heroku
Wait until the push is successful and you get the local prompt back.
Then log in to heroku and there execute migrate.
To do this in one execution environment, do not launch these as individual heroku commands, but launch a bash shell and execute both commands in there: (do not type the '~$', this represents the Heroku prompt)
heroku run bash
~$ ./manage.py migrate
~$ exit
You must not run makemigrations via heroku run. You must run it locally, and commit the result to git. Then you can deploy that code and run those generated migrations via heroku run python manage.py migrate.
The reason is that heroku run spins up a new dyno each time, with a new filesystem, so any migrations generated in the first command are lost by the time the second command runs. But in any case, migrations are part of your code, and must be in version control.
As Heroku's dynos don't have a filesystem that persists across deploys, a file-based database like SQLite3 isn't going to be suitable. It's a great DB for development/quick prototypes, though. https://stackoverflow.com/a/31395988/784648
So between deploys your entire SQLite database is going to be wiped, you should move onto a dedicated database when you deploy to heroku I think. I know heroku has a free tier for postgres databases which I'd recommend if you just want to test deployment to heroku.
python manage.py makemigrations
python manage.py migrate
python manage.py migrate --run-syncdb
this worked for me.
I know this is old, but I had this issue and found this thread useful.
To sum up, the error can also appear when executing the migrations (which is supposed to create the needed relations in the DB), because recent versions of Django check your urls.py before doing the migrations. In my case - and in many others' it seems, loading urls.py meant loading the views, and some views were class-based and had an attribute defined through get_object_or_404:
class CustomView(ParentCustomView):
phase = get_object_or_404(Phase, code='C')
This is what was evaluated before the migrations actually ran, and caused the error. I fixed it by turning my view's attribute as a property:
class CustomView(ParentCustomView):
#property
def phase(self):
return get_object_or_404(Phase, code='C')
You'll know quite easily if this is the problem you are encountering, as the Traceback will point you towards the problematic view.
Also this problem might not appear in development because you have migrated before creating the view.

Django does not install model tables

In my project, I have a routers.py with different router classes. Now, I am making a new app. I have created my models.py. I have also registered the app in the INSTALLED_APPS in settings.py. Then, I ran validate. Everything is fine. When I syncd thoughb, Django does not install the tables. I tried using
python manage.py sqlall <app_name> | psql <database>
Then, I get an error message saying:
psql: FATAL: password authentication failed for user <user name>
I noticed that the role does not exist in postgres. So, I created the role with login privilege createdb and password. Then, I get a different error message:
psql: FATAL: password authentication failed for user <user name>
close failed in file object destructor:
Error in sys.excepthook:
Original exception was:
And, it does not provide the original exception.
Any help is much appreciated.
It looks like the Django application is unable to log onto the DB.
In django's settings.py make sure you have the proper DB credentials setup:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'HOST': get_env_variable("DJANGO_DB_HOST"),
'NAME': get_env_variable("DJANGO_DB_NAME"),
'USER': get_env_variable("DJANGO_DB_USER"),
'PASSWORD': get_env_variable("DJANGO_DB_PWD"),
'PORT': '',
},
...
}
As you can see my credentials are grabbed from environment variables. You can hardcode them in for test purposes.
Then in the DB (mine is postgresql) create the user/grant it the correct privileges, for example:
ssh root#dbhost
su - postgres
createdb dbname
psql
GRANT ALL PRIVILEGES ON DATABASE dbname TO dbuser
That should do.
I recommend the following steps as well, if they are missing from your setup:
In your app's admin.py register your models with Django's admin:
# Register your models here.
admin.site.register(Model1)
...
admin.site.register(ModelN)
Then, assuming you have created the project already, run:
python manage.py migrate
(it's the syncdb equivalent. Read the docs about migrations).
If that command does not ask for the admin superuser then create your administrative user (i.e. the user who can manipulate the models through django's admin interface) with:
python manage.py createsuperuser
Fire up Django
python manage.py runserver 0.0.0.0:8000
and see what happens whan you visit your site and admin at
localhost:8000/
localhost:8000/admin
Please pardon me if you know all those things already. That is what I normally do in my dev environment (I also use virtualenv, of course).

"no such table" error on Heroku after django syncdb passed

I'm trying to deploy my Django application to Heroku. The migrations are in my local Git. When I try:
git push heroku master
heroku run python manage.py syncdb
It applies the migrations and also promts me to create superuser, which I successfully do. Now the application is up and running, however when I try to log into the Django admin it's throwing:
OperationalError no such table: user_user
When I try
heroku run python manage.py makemigrations
heroku run python manage.py migrate
heroku run python manage.py createsuperuser
It applies all migrations, but fails to create superuser throwing:
django.db.utils.OperationalError: no such table: user_user
Either way I can not have my database set up and migrated on Heroku.
My database settings are:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
My user model is:
class User(AbstractUser):
rating = models.PositiveIntegerField(default=settings.DEFAULT_USER_RATING)
Django version is 1.7.1.
How do I get my database tables created on Heroku?
You must not use sqlite3 on Heroku.
sqlite stores the database as a file on disk. But the filesystem in a Heroku dyno is not persistent, and is not shared between dynos. So, when you do heroku run python manage.py migrate, Heroku spins up a new dyno with a blank database, runs the migrations, then deletes the dyno and the database. The dyno that's running your site is unaffected, and never gets migrated.
You must use one of the Heroku database add-ons. There is a free tier for Postgres. You should use the dj-database-url library to set your database settings dynamically from the environment variables which Heroku sets.
Also, for the same reason, you must do manage.py makemigrations locally, commit the result to git, then push to Heroku.
You can use postgresql:
In settings.py add(at the end of file):
# ie if Heroku server
if 'DATABASE_URL' in os.environ:
import dj_database_url
DATABASES = {'default': dj_database_url.config()}
In requirements.txt add:
dj-database-url
psycopg2
Now you can run:
heroku run python manage.py migrate
pip install django-heroku
Add import django_heroku at top of file settings.py
Place django_heroku.settings(locals()) at the very bottom of settings.py
It will automatically configure your db. You can learn more on their website
What version of django you are using..?
If you are using django>=1.7 you need to run migrate
After adding models you need to do
python manage.py makemigrations then python manage.py migrate
If your project already contain migrations you can directly run python manage.py migrate command.
If you miss any step mentioned above please do that.

Running Django with gunicorn: Bad Request (400)

I am following this tutorial to set up a Django application and serve it with Gunicorn on a Debian DigitalOcean server: http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/
I have got as far as the section starting "Now that you have gunicorn, you can test whether it can serve your Django application by running the following command". Now I'm stuck.
In other words, I can successfully run the application using python manage.py runserver, but not by using gunicorn.
I've successfully accessed my app with:
$ python manage.py runserver xx.xx.xx.xx:8000
Now from the same directory, I'm trying to run:
$ gunicorn my_django.wsgi:application --bind xx.xx.xx.xx:8001
It appears to start OK, but when I go to http://xx.xx.xx.xx:8001, I see:
Bad Request (400)
I'm not sure how to debug this: there's nothing in /var/log/gunicorn/.
I have set ALLOWED_HOSTS=['xx.xx.xx.xx'] in my settings file.
UPDATE: Being an idiot: gunicorn was looking in production settings file, not local settings file. Setting the ALLOWED_HOSTS in production settings fixed it.
I'd still really like to know how to debug problems like this though.
The answer: gunicorn was looking in production settings file, not local settings file. Setting the ALLOWED_HOSTS in production settings fixed it.

Categories